1
2
3
4
5
6
7
8
9
10
11
12
13
14 package org.eclipse.jetty.security.authentication;
15
16 import java.io.IOException;
17
18 import javax.servlet.ServletRequest;
19 import javax.servlet.ServletResponse;
20 import javax.servlet.http.HttpServletRequest;
21 import javax.servlet.http.HttpServletResponse;
22
23 import org.eclipse.jetty.http.HttpHeaders;
24 import org.eclipse.jetty.http.security.Constraint;
25 import org.eclipse.jetty.security.ServerAuthException;
26 import org.eclipse.jetty.security.UserAuthentication;
27 import org.eclipse.jetty.server.Authentication;
28 import org.eclipse.jetty.server.UserIdentity;
29 import org.eclipse.jetty.server.Authentication.User;
30 import org.eclipse.jetty.util.B64Code;
31 import org.eclipse.jetty.util.StringUtil;
32
33
34
35
36 public class BasicAuthenticator extends LoginAuthenticator
37 {
38
39 public BasicAuthenticator()
40 {
41 }
42
43
44
45
46
47 public String getAuthMethod()
48 {
49 return Constraint.__BASIC_AUTH;
50 }
51
52
53
54
55
56 public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException
57 {
58 HttpServletRequest request = (HttpServletRequest)req;
59 HttpServletResponse response = (HttpServletResponse)res;
60 String credentials = request.getHeader(HttpHeaders.AUTHORIZATION);
61
62 try
63 {
64 if (!mandatory)
65 return _deferred;
66
67 if (credentials != null)
68 {
69 credentials = credentials.substring(credentials.indexOf(' ')+1);
70 credentials = B64Code.decode(credentials,StringUtil.__ISO_8859_1);
71 int i = credentials.indexOf(':');
72 if (i>0)
73 {
74 String username = credentials.substring(0,i);
75 String password = credentials.substring(i+1);
76
77 UserIdentity user = _loginService.login(username,password);
78 if (user!=null)
79 {
80 renewSessionOnAuthentication(request,response);
81 return new UserAuthentication(getAuthMethod(),user);
82 }
83 }
84 }
85
86 if (_deferred.isDeferred(response))
87 return Authentication.UNAUTHENTICATED;
88
89 response.setHeader(HttpHeaders.WWW_AUTHENTICATE, "basic realm=\"" + _loginService.getName() + '"');
90 response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
91 return Authentication.SEND_CONTINUE;
92 }
93 catch (IOException e)
94 {
95 throw new ServerAuthException(e);
96 }
97 }
98
99 public boolean secureResponse(ServletRequest req, ServletResponse res, boolean mandatory, User validatedUser) throws ServerAuthException
100 {
101 return true;
102 }
103
104 }