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