Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidillsley/20d0956966e800bd03bb to your computer and use it in GitHub Desktop.
Save davidillsley/20d0956966e800bd03bb to your computer and use it in GitHub Desktop.
Hardcoded Basic-Auth authenticator for Play2/Java
import play.mvc.Http;
import play.mvc.Result;
import play.mvc.Security;
import java.nio.charset.Charset;
import java.util.Base64;
import static java.util.Optional.ofNullable;
/**
* A very simple basic auth username/password authenticator for use with Play2/Java.
*
* Extracts the username/password from environment variables and defaults to username/password
*
* Environment variables used are "BASIC_AUTH_USERNAME" and "BASIC_AUTH_PASSWORD"
*
* Apply to a Play2 controller method with:
*
* @Security.Authenticated(SingleUserBasicAuthAuthenticator.class)
*
* @see play.mvc.Security.Authenticated
*/
public class SingleUserBasicAuthAuthenticator extends Security.Authenticator {
private static final Charset UTF8 = Charset.forName("UTF-8");
private static final Base64.Decoder DECODER = Base64.getDecoder();
private static final String USERNAME = ofNullable(System.getenv("BASIC_AUTH_USERNAME")).orElse("username");
private static final String PASSWORD = ofNullable(System.getenv("BASIC_AUTH_PASSWORD")).orElse("password");
public String getUsername(Http.Context ctx) {
String authorization = ctx.request().getHeader(Http.HeaderNames.AUTHORIZATION);
if (authorization != null) {
String[] basicParts = authorization.split(" ", 2);
if (basicParts.length == 2) {
String decoded = new String(DECODER.decode(basicParts[1]), UTF8);
String[] parts = decoded.split(":", 2);
if (parts.length == 2
&& USERNAME.equals(parts[0])
&& PASSWORD.equals(parts[1])) {
return USERNAME;
}
}
}
return null;
}
public Result onUnauthorized(Http.Context ctx) {
ctx.response().setHeader(Http.HeaderNames.WWW_AUTHENTICATE, "Basic realm=\"Please enter details provided\"");
return unauthorized(views.html.defaultpages.unauthorized.render());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment