Mercurial Hosting > luan
view src/luan/modules/http/AuthenticationHandler.java @ 1000:32d4b569567c
simplify handle()
author | Franklin Schmidt <fschmidt@gmail.com> |
---|---|
date | Wed, 19 Oct 2016 04:22:51 -0600 |
parents | b3176fd168bf |
children | 0d884377e923 |
line wrap: on
line source
package luan.modules.http; import java.io.IOException; import java.util.Base64; import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.handler.AbstractHandler; public class AuthenticationHandler extends AbstractHandler { private final String path; private String password = "password"; public AuthenticationHandler(String path) { this.path = path; } public void setPassword(String password) { this.password = password; } @Override public void handle(String target,Request request,HttpServletResponse response) throws IOException { if( !target.startsWith(path) ) return; String pwd = getPassword(request); if( password.equals(pwd) ) return; response.setHeader("WWW-Authenticate","Basic realm=\""+path+"\""); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); request.setHandled(true); } private static String getPassword(Request request) { String auth = request.getHeader("Authorization"); if( auth==null ) return null; String[] a = auth.split(" +"); if( a.length != 2 ) throw new RuntimeException("auth = "+auth); if( !a[0].equals("Basic") ) throw new RuntimeException("auth = "+auth); auth = new String(Base64.getDecoder().decode(a[1])); a = auth.split(":"); if( a.length != 2 ) throw new RuntimeException("auth = "+auth); return a[1]; } }