Created
November 22, 2012 11:26
-
-
Save danielreuterwall/4130675 to your computer and use it in GitHub Desktop.
Basic authorization in Play
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.IOException; | |
import java.lang.reflect.Method; | |
import play.Application; | |
import play.Logger; | |
import play.GlobalSettings; | |
import play.Configuration; | |
import play.mvc.Http.Request; | |
import play.mvc.Action; | |
import play.mvc.Http; | |
import play.mvc.Result; | |
import static play.mvc.Http.HeaderNames.WWW_AUTHENTICATE; | |
import static play.mvc.Http.HeaderNames.AUTHORIZATION; | |
import static play.mvc.Action.Simple.unauthorized; | |
public class Global extends GlobalSettings { | |
boolean protectAll; | |
@Override | |
public void onStart(Application app) { | |
Configuration conf = Configuration.root(); | |
protectAll = conf.getBoolean("basicAuth.protectAll"); | |
if(protectAll) { | |
Logger.info("Will protect all requests with basic authorization"); | |
} | |
} | |
@Override | |
public Action onRequest(Request request, Method actionMethod) { | |
Action action = null; | |
if(protectAll) { | |
action = basicAuth(request, actionMethod); | |
} | |
return action != null ? action : super.onRequest(request, actionMethod); | |
} | |
public Action basicAuth(Request request, Method actionMethod) { | |
String authHeader = request.getHeader(AUTHORIZATION); | |
if (authHeader == null) { | |
return unauthorizedAction(); | |
} | |
String auth = authHeader.substring(6); | |
try { | |
byte[] decodedAuth = new sun.misc.BASE64Decoder().decodeBuffer(auth); | |
String[] credString = new String(decodedAuth, "UTF-8").split(":"); | |
if (credString == null || credString.length != 2) { | |
return unauthorizedAction(); | |
} | |
String username = credString[0]; | |
String password = credString[1]; | |
if(!validCredentials(username, password)) { | |
return unauthorizedAction(); | |
} | |
return null; | |
} | |
catch(IOException e) { | |
return unauthorizedAction(); | |
} | |
} | |
public Action unauthorizedAction() { | |
return new UnauthorizedAction(); | |
} | |
class UnauthorizedAction extends Action { | |
private static final String REALM = "Basic realm=\"Access is restricted\""; | |
@Override | |
public Result call(Http.Context context) throws Throwable { | |
context.response().setHeader(WWW_AUTHENTICATE, REALM); | |
return unauthorized(); | |
} | |
} | |
public boolean validCredentials(String username, String password) { | |
return "test:test".equals(username + ":" + password); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment