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