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:
- Request for a certain page is sent to the server
- On the server the header with the name “Authorization” is looked up
- If it exists the contained string is parsed. It’s in the format “name:pwd”. Then name and pwd are checked.
- 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.