Mercurial Hosting > luan
diff src/goodjava/webserver/handlers/BasicAuthHandler.java @ 1608:f7e3adae4907
add BasicAuthHandler
author | Franklin Schmidt <fschmidt@gmail.com> |
---|---|
date | Sat, 01 May 2021 19:52:56 -0600 |
parents | |
children | 268b2a26e8d7 |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/goodjava/webserver/handlers/BasicAuthHandler.java Sat May 01 19:52:56 2021 -0600 @@ -0,0 +1,39 @@ +package goodjava.webserver.handlers; + +import goodjava.util.GoodUtils; +import goodjava.webserver.Handler; +import goodjava.webserver.Request; +import goodjava.webserver.Response; +import goodjava.webserver.Status; + + +public class BasicAuthHandler implements Handler { + private final Handler handler; + private final String realm; + private final String match; + + public BasicAuthHandler(Handler handler,String realm,String username,String password) { + this.handler = handler; + this.realm = realm; + this.match = GoodUtils.base64Encode(username+":"+password); + } + + private Response unauthorized() { + Response response = new Response(); + response.status = Status.UNAUTHORIZED; + response.headers.put("WWW-Authenticate","Basic realm=\""+realm+"\""); + return response; + } + + public Response handle(Request request) { + String auth = (String)request.headers.get("Authorization"); + if( auth==null ) + return unauthorized(); + String[] a = auth.split(" "); + if( a.length!=2 || !a[0].equals("Basic") || !a[1].equals(match) ) + return unauthorized(); + Response response = handler.handle(request); + response.headers.put("X-Accel-Expires","0"); + return response; + } +}