1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package org.mortbay.jetty.security;
16
17 import java.io.IOException;
18 import java.security.Principal;
19
20 import javax.servlet.http.HttpServletResponse;
21
22 import org.mortbay.jetty.HttpHeaders;
23 import org.mortbay.jetty.Request;
24 import org.mortbay.jetty.Response;
25 import org.mortbay.log.Log;
26 import org.mortbay.util.StringUtil;
27
28
29
30
31
32
33 public class BasicAuthenticator implements Authenticator
34 {
35
36
37
38
39
40
41
42 public Principal authenticate(UserRealm realm,
43 String pathInContext,
44 Request request,
45 Response response)
46 throws IOException
47 {
48
49 Principal user=null;
50 String credentials = request.getHeader(HttpHeaders.AUTHORIZATION);
51
52 if (credentials!=null )
53 {
54 try
55 {
56 if(Log.isDebugEnabled())Log.debug("Credentials: "+credentials);
57 credentials = credentials.substring(credentials.indexOf(' ')+1);
58 credentials = B64Code.decode(credentials,StringUtil.__ISO_8859_1);
59 int i = credentials.indexOf(':');
60 String username = credentials.substring(0,i);
61 String password = credentials.substring(i+1);
62 user = realm.authenticate(username,password,request);
63
64 if (user==null)
65 {
66 Log.warn("AUTH FAILURE: user {}",StringUtil.printable(username));
67 }
68 else
69 {
70 request.setAuthType(Constraint.__BASIC_AUTH);
71 request.setUserPrincipal(user);
72 }
73 }
74 catch (Exception e)
75 {
76 Log.warn("AUTH FAILURE: "+e.toString());
77 Log.ignore(e);
78 }
79 }
80
81
82 if (user==null && response!=null)
83 sendChallenge(realm,response);
84
85 return user;
86 }
87
88
89 public String getAuthMethod()
90 {
91 return Constraint.__BASIC_AUTH;
92 }
93
94
95 public void sendChallenge(UserRealm realm,Response response)
96 throws IOException
97 {
98 response.setHeader(HttpHeaders.WWW_AUTHENTICATE, "Basic realm=\""+realm.getName()+'"');
99 response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
100 }
101
102 }
103