Thank you very much for taking the time and giving me feedback.
Visitors are also reading...
← PreviousNext →

HTTP Basic Authentication - Thank you PlayFramework!

07 Jun 2011

Finally, one of my mysteries is resolved.

Do you know how it is when you need a basic authentication in a browser?
You get this weird default popup asking for user/password.
You’ve probably seen it by now, but just in case you haven’t you can click here to see it in action.
And if that link does not work, it looks something like :

I always wondered how you can tell the browser to prompt this dialog.
Today I found out thanks to play!framework

Looking at the “Controller” code, you will find the method “unauthorized” that you can use like this ( action “index” in Controller “Application”) :

public static void index() {
  String password = request.password;

if ( password == null )
        unauthorized( "My Realm" );

This will cause the prompt to appear, and the string “My Realm” will be used in the prompt.
Digging a little bit in the play!Framework code, you will find the following code :

public class Unauthorized extends Result {

    String realm;  

    public Unauthorized(String realm) {  
        this.realm = realm;  

    public void apply(Request request, Response response) {  
        response.status = 401;  
        response.setHeader("WWW-Authenticate", "Basic realm=\"" + realm + "\"");  

Which means - in order to get the browser to show the basic authentication, you need to return “401” - and add “Basic Realm” to the header as shown above.
The browser will detect this, prompt User/Password and will make the same request. Only this time adding the “username/password” to the request for you to read.

← PreviousNext →