Token-based authentication using the Play 2 platform

I am building an application using Play Framework 2 in Scala. It will be purely RESTful, with moments of calls currently being made from a single page Javascript application.

What would be the best way to integrate token authentication? There are several authentication libraries for Play2, as well as the raw Secured feature, but it is not clear which one will be the most convenient.

Thanks for your help and your suggestions.

+7
authentication rest scala playframework
source share
2 answers

If you are referencing JWT when you say token-based, you can take a look at this example of implementing basic HTTP authentication in Play2, and this answer is re: how to implement JWT on the Scala backend. The good part is that you do not need cookies or cache for authenticated users.

Including content from the 1st link for convenience:

 def Secured[A](username: String, password: String)(action: Action[A]) = Action(action.parser) { request => request.headers.get("Authorization").flatMap { authorization => authorization.split(" ").drop(1).headOption.filter { encoded => new String(org.apache.commons.codec.binary.Base64.decodeBase64(encoded.getBytes)).split(":").toList match { case u :: p :: Nil if u == username && password == p => true case _ => false } }.map(_ => action(request)) }.getOrElse { Unauthorized.withHeaders("WWW-Authenticate" -> """Basic realm="Secured"""") } } 

Use the following:

 def myAction = Secured("admin", "1234secret") { Action { request => Ok } } 
+6
source share

I think you should take a look at James Ward's approach here .

Briefly approaches:

  • The user requests an index page and downloads a one-page application.
  • The application is trying to find out if there is a security token stored in browser cookies (or you can use localStorage)
  • If there is no token, the login page is displayed.
  • If a token is present, we believe that we have already authenticated
  • The application is trying to get some data from the server using a token in a custom header (for example, X-AUTH-TOKEN)
  • The server checks the token and responds with data, if everything is in order
  • If the token is invalid, the server responds 401, and then go to step 3
  • Each request to your server uses the same token

If you want to delve into the details, feel free to ask more questions!

+4
source share

All Articles