Skip to content

Instantly share code, notes, and snippets.

@danielreuterwall
Created November 22, 2012 11:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielreuterwall/4130675 to your computer and use it in GitHub Desktop.
Save danielreuterwall/4130675 to your computer and use it in GitHub Desktop.
Basic authorization in Play
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