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
62
63 public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException
64 {
65 HttpServletRequest request = (HttpServletRequest)req;
66 HttpServletResponse response = (HttpServletResponse)res;
67 String credentials = request.getHeader(HttpHeaders.AUTHORIZATION);
68
69 try
70 {
71 if (!mandatory)
72 return new DeferredAuthentication(this);
73
74 if (credentials != null)
75 {
76 int space=credentials.indexOf(' ');
77 if (space>0)
78 {
79 String method=credentials.substring(0,space);
80 if ("basic".equalsIgnoreCase(method))
81 {
82 credentials = credentials.substring(space+1);
83 credentials = B64Code.decode(credentials,StringUtil.__ISO_8859_1);
84 int i = credentials.indexOf(':');
85 if (i>0)
86 {
87 String username = credentials.substring(0,i);
88 String password = credentials.substring(i+1);
89
90 UserIdentity user = login (username, password, request);
91 if (user!=null)
92 {
93 return new UserAuthentication(getAuthMethod(),user);
94 }
95 }
96 }
97 }
98 }
99
100 if (DeferredAuthentication.isDeferred(response))
101 return Authentication.UNAUTHENTICATED;
102
103 response.setHeader(HttpHeaders.WWW_AUTHENTICATE, "basic realm=\"" + _loginService.getName() + '"');
104 response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
105 return Authentication.SEND_CONTINUE;
106 }
107 catch (IOException e)
108 {
109 throw new ServerAuthException(e);
110 }
111 }
112
113 public boolean secureResponse(ServletRequest req, ServletResponse res, boolean mandatory, User validatedUser) throws ServerAuthException
114 {
115 return true;
116 }
117
118 }