Skip to content

Instantly share code, notes, and snippets.

@joergviola
Created May 4, 2012 13:39
Show Gist options
  • Save joergviola/2594860 to your computer and use it in GitHub Desktop.
Save joergviola/2594860 to your computer and use it in GitHub Desktop.
Basic Auth a whole Play 2.0 Application
public class Global extends GlobalSettings {
@Override
public Action onRequest(Request arg0, Method arg1) {
return new Action.Simple() {
public Result call(Context ctx) throws Throwable {
String authConf = Config.getString("basic.auth");
if (authConf == null)
return delegate.call(ctx);
String auth = ctx.request().getHeader("Authorization");
if (auth == null)
return authorize(ctx);
String[] comps = auth.split(" ");
if (comps.length != 2)
return authorize(ctx);
if (!"Basic".equals(comps[0]))
return authorize(ctx);
BASE64Decoder decoder = new sun.misc.BASE64Decoder();
String credentials = new String(decoder.decodeBuffer(comps[1]));
if (authConf.equals(credentials))
return delegate.call(ctx);
return authorize(ctx);
}
private Result authorize(Context ctx) {
ctx.response().setHeader("WWW-Authenticate",
"Basic realm=\"Secure-Me\"");
return unauthorized();
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment