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