1 16 package org.mortbay.http; 17 18 import java.io.IOException ; 19 import java.security.Principal ; 20 21 import org.apache.commons.logging.Log; 22 import org.mortbay.log.LogFactory; 23 import org.mortbay.util.B64Code; 24 import org.mortbay.util.LogSupport; 25 import org.mortbay.util.StringUtil; 26 27 28 33 public class BasicAuthenticator implements Authenticator 34 { 35 private static Log log = LogFactory.getLog(BasicAuthenticator.class); 36 37 38 44 public Principal authenticate(UserRealm realm, 45 String pathInContext, 46 HttpRequest request, 47 HttpResponse response) 48 throws IOException 49 { 50 Principal user=null; 52 String credentials = request.getField(HttpFields.__Authorization); 53 54 if (credentials!=null ) 55 { 56 try 57 { 58 if(log.isDebugEnabled())log.debug("Credentials: "+credentials); 59 credentials = credentials.substring(credentials.indexOf(' ')+1); 60 credentials = B64Code.decode(credentials,StringUtil.__ISO_8859_1); 61 int i = credentials.indexOf(':'); 62 String username = credentials.substring(0,i); 63 String password = credentials.substring(i+1); 64 user = realm.authenticate(username,password,request); 65 66 if (user==null) 67 log.warn("AUTH FAILURE: user "+username); 68 else 69 { 70 request.setAuthType(SecurityConstraint.__BASIC_AUTH); 71 request.setAuthUser(username); 72 request.setUserPrincipal(user); 73 } 74 } 75 catch (Exception e) 76 { 77 log.warn("AUTH FAILURE: "+e.toString()); 78 LogSupport.ignore(log,e); 79 } 80 } 81 82 if (user==null && response!=null) 84 sendChallenge(realm,response); 85 86 return user; 87 } 88 89 90 public String getAuthMethod() 91 { 92 return SecurityConstraint.__BASIC_AUTH; 93 } 94 95 96 public void sendChallenge(UserRealm realm, 97 HttpResponse response) 98 throws IOException 99 { 100 response.setField(HttpFields.__WwwAuthenticate, 101 "basic realm=\""+realm.getName()+'"'); 102 response.sendError(HttpResponse.__401_Unauthorized); 103 } 104 105 } 106 107 | Popular Tags |