1 28 29 package com.caucho.server.security; 30 31 import com.caucho.util.Base64; 32 33 import javax.servlet.ServletContext ; 34 import javax.servlet.ServletException ; 35 import javax.servlet.http.HttpServletRequest ; 36 import javax.servlet.http.HttpServletResponse ; 37 import java.io.IOException ; 38 import java.security.Principal ; 39 import java.util.logging.Level ; 40 41 45 public class BasicLogin extends AbstractLogin { 46 protected String _realm; 47 48 51 public void setRealmName(String realm) 52 { 53 _realm = realm; 54 } 55 56 59 public String getRealmName() 60 { 61 return _realm; 62 } 63 64 67 public String getAuthType() 68 { 69 return "Basic"; 70 } 71 72 83 public Principal authenticate(HttpServletRequest request, 84 HttpServletResponse response, 85 ServletContext application) 86 throws ServletException , IOException 87 { 88 Principal user; 89 90 ServletAuthenticator auth = getAuthenticator(); 91 92 user = auth.getUserPrincipal(request, response, application); 94 if (user != null) 95 return user; 96 97 user = getBasicPrincipal(request, response, application); 98 99 if (user != null) 100 return user; 101 102 sendBasicChallenge(response); 103 104 return null; 105 } 106 107 116 public Principal getUserPrincipal(HttpServletRequest request, 117 HttpServletResponse response, 118 ServletContext application) 119 throws ServletException 120 { 121 ServletAuthenticator auth = getAuthenticator(); 122 123 Principal user = auth.getUserPrincipal(request, response, application); 124 125 if (user != null) 126 return user; 127 128 return getBasicPrincipal(request, response, application); 129 } 130 131 134 protected void sendBasicChallenge(HttpServletResponse res) 135 throws ServletException , IOException 136 { 137 String realm = getRealmName(); 138 if (realm == null) 139 realm = "resin"; 140 141 res.setHeader("WWW-Authenticate", "Basic realm=\"" + realm + "\""); 142 res.sendError(res.SC_UNAUTHORIZED); 143 } 144 145 150 protected Principal getBasicPrincipal(HttpServletRequest request, 151 HttpServletResponse response, 152 ServletContext application) 153 throws ServletException 154 { 155 Principal principal; 156 157 principal = (Principal ) request.getAttribute(AbstractAuthenticator.LOGIN_NAME); 159 if (principal != null) 160 return principal; 161 162 String value = request.getHeader("authorization"); 163 if (value == null) 164 return null; 165 166 int i = value.indexOf(' '); 167 if (i <= 0) 168 return null; 169 170 String decoded = Base64.decode(value.substring(i + 1)); 171 172 int index = decoded.indexOf(':'); 173 if (index < 0) 174 return null; 175 176 String user = decoded.substring(0, index); 177 String password = decoded.substring(index + 1); 178 179 ServletAuthenticator auth = getAuthenticator(); 180 principal = auth.login(request, response, application, user, password); 181 182 if (log.isLoggable(Level.FINE)) 183 log.fine("basic: " + user + " -> " + principal); 184 185 return principal; 186 } 187 } 188 | Popular Tags |