nojo
nojo

Reputation: 1065

Return a 401 when unauthenticated in Play

The behavior of the Secure module in play (1.2.4 if it's relevant) is to 302 redirect to the login page. This is appropriate enough for most web pages. I've got some routes which are used in AJAX calls. For these, I'd like to return a 401 when the user is unauthenticated, rather than returning a redirect.

How can I customize what Play does when authentication fails?

Upvotes: 1

Views: 657

Answers (1)

Tommi
Tommi

Reputation: 8608

Secure module is one of the simplest Play modules. I see it as a starting point, or an example, from where you can build your own, more complex authentication implementations. Therefore, my advice is to copy the contents of the module straight into your project (thus essentially taking away the actual module dependency).

Then, you can modify it as you wish - most of the logic is in a single controller called Secure. For example, the behaviour you described can be easily achieved by modifying the authenticate method. Take a look at the below snippet from the method - the line in comments has been added by me:

...
if(validation.hasErrors() || !allowed) {
    flash.keep("url");
    flash.error("secure.error");
    params.flash();
    // you can check if ("POST".equalsIgnoreCase(request.method)) here...
    login();
}
...

Upvotes: 1

Related Questions