Basic authentication with Play! 2

I recently had the problem that I wanted to secure a page preview we developed with basic authentication. Easy thing I thought. But it wasn’t. I was used to the use of frameworks/containers like tomcat, which provide easy means to do such things. With Play! though you don’t have such things. You’ll have to do it yourself.

The good thing is that you’ll understand what is actually going on:

The basic stuff happening is:

  1. Request for a certain page is sent to the server
  2. On the server the header with the name “Authorization” is looked up
  3. If it exists the contained string is parsed. It’s in the format “name:pwd”. Then name and pwd are checked.
  4. If either the header does not exist or nam/pwd are incorrect an unauthorized 401 response with a header of name “WWW-Authenticate” and a content that must contain the word basic is sent. This lets the browser know what actually to do.

Thats pretty much it. With Play! 1 this was pretty easy as you had direct access to the response as you might be used to in several MVC frameworks. With Play! 2 this is not so obvious although also really easy:

You can add a header to the response by using the method withHeaders. A good example can be found here.

At the time I needed it, I was unable to find an example in the net. Now as I wanted to finish this post and made another quick query and immediately found the example of Guillaume Bort. As he develops the play framework I decided to just add the link here without any code.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s