1608
|
1 package goodjava.webserver.handlers;
|
|
2
|
|
3 import goodjava.util.GoodUtils;
|
|
4 import goodjava.webserver.Handler;
|
|
5 import goodjava.webserver.Request;
|
|
6 import goodjava.webserver.Response;
|
|
7 import goodjava.webserver.Status;
|
|
8
|
|
9
|
|
10 public class BasicAuthHandler implements Handler {
|
|
11 private final Handler handler;
|
|
12 private final String realm;
|
|
13 private final String match;
|
|
14
|
|
15 public BasicAuthHandler(Handler handler,String realm,String username,String password) {
|
|
16 this.handler = handler;
|
|
17 this.realm = realm;
|
|
18 this.match = GoodUtils.base64Encode(username+":"+password);
|
|
19 }
|
|
20
|
|
21 private Response unauthorized() {
|
|
22 Response response = new Response();
|
|
23 response.status = Status.UNAUTHORIZED;
|
|
24 response.headers.put("WWW-Authenticate","Basic realm=\""+realm+"\"");
|
|
25 return response;
|
|
26 }
|
|
27
|
|
28 public Response handle(Request request) {
|
|
29 String auth = (String)request.headers.get("Authorization");
|
|
30 if( auth==null )
|
|
31 return unauthorized();
|
|
32 String[] a = auth.split(" ");
|
|
33 if( a.length!=2 || !a[0].equals("Basic") || !a[1].equals(match) )
|
|
34 return unauthorized();
|
|
35 Response response = handler.handle(request);
|
|
36 response.headers.put("X-Accel-Expires","0");
|
|
37 return response;
|
|
38 }
|
|
39 }
|