comparison src/luan/modules/http/jetty/AuthenticationHandler.java @ 1136:d30d400fd43d

add http/jetty
author Franklin Schmidt <fschmidt@gmail.com>
date Mon, 29 Jan 2018 17:50:49 -0700
parents src/luan/modules/http/AuthenticationHandler.java@0d884377e923
children
comparison
equal deleted inserted replaced
1135:707a5d874f3e 1136:d30d400fd43d
1 package luan.modules.http.jetty;
2
3 import java.io.IOException;
4 import javax.servlet.http.HttpServletRequest;
5 import javax.servlet.http.HttpServletResponse;
6 import org.eclipse.jetty.server.Request;
7 import org.eclipse.jetty.server.handler.AbstractHandler;
8 import org.eclipse.jetty.util.B64Code;
9
10
11 public class AuthenticationHandler extends AbstractHandler {
12 private final String path;
13 private String password = "password";
14
15 public AuthenticationHandler(String path) {
16 this.path = path;
17 }
18
19 public void setPassword(String password) {
20 this.password = password;
21 }
22
23 public void handle(String target,Request baseRequest,HttpServletRequest request,HttpServletResponse response)
24 throws IOException
25 {
26 if( !target.startsWith(path) )
27 return;
28 String pwd = getPassword(request);
29 if( password.equals(pwd) )
30 return;
31 response.setHeader("WWW-Authenticate","Basic realm=\""+path+"\"");
32 response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
33 baseRequest.setHandled(true);
34 }
35
36 private static String getPassword(HttpServletRequest request) {
37 String auth = request.getHeader("Authorization");
38 if( auth==null )
39 return null;
40 String[] a = auth.split(" +");
41 if( a.length != 2 )
42 throw new RuntimeException("auth = "+auth);
43 if( !a[0].equals("Basic") )
44 throw new RuntimeException("auth = "+auth);
45 auth = new String(B64Code.decode(a[1]));
46 a = auth.split(":");
47 if( a.length != 2 )
48 throw new RuntimeException("auth = "+auth);
49 return a[1];
50 }
51 }