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.Authenticator;
23 import org.mortbay.jetty.HttpHeaders;
24 import org.mortbay.jetty.Request;
25 import org.mortbay.jetty.Response;
26 import org.mortbay.jetty.UserRealm;
27 import org.mortbay.log.Log;
28 import org.mortbay.util.StringUtil;
29
30
31
32
33
34
35 public class BasicAuthenticator implements Authenticator
36 {
37
38
39
40
41
42
43
44 public Principal authenticate(UserRealm realm,
45 String pathInContext,
46 Request request,
47 Response response)
48 throws IOException
49 {
50
51 Principal user=null;
52 String credentials = request.getHeader(HttpHeaders.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 {
68 Log.warn("AUTH FAILURE: user {}",StringUtil.printable(username));
69 }
70 else
71 {
72 request.setAuthType(Constraint.__BASIC_AUTH);
73 request.setUserPrincipal(user);
74 }
75 }
76 catch (Exception e)
77 {
78 Log.warn("AUTH FAILURE: "+e.toString());
79 Log.ignore(e);
80 }
81 }
82
83
84 if (user==null && response!=null)
85 sendChallenge(realm,response);
86
87 return user;
88 }
89
90
91 public String getAuthMethod()
92 {
93 return Constraint.__BASIC_AUTH;
94 }
95
96
97 public void sendChallenge(UserRealm realm,Response response)
98 throws IOException
99 {
100 response.setHeader(HttpHeaders.WWW_AUTHENTICATE, "Basic realm=\""+realm.getName()+'"');
101 response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
102 }
103
104 }
105