質問

I'm buiding an application using Play Framework 2, in Scala. It will be purely RESTful, with calls being made at the moment from a Javascript single page application.

What would be the best way to integrate token-based authentication? There are multiple authentication libraries for Play2 out there, plus the raw Secured trait, but it's not clear which one would be the most convenient.

Thanks for your help and your suggestions

正しい解決策はありません

他のヒント

In case you refer to JWT when you say "token-based", you may want to take a look at this example of implementing HTTP Basic Authentication in Play2, and this answer re: how to implement JWT on a Scala backend. The nice part is that you need neither cookies, nor a cache for authenticated users.

Including content from 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 as follows:

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

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

The approach in short is quite straight forward:

  1. User requests index page and loads your single-page application
  2. Application tries to figure out if there is a security token stored in browser's cookies (or you can use localStorage)
  3. If there is no token – login page is displayed
  4. If token is present – we think that we're already authenticated
  5. App tries to fetch some data from server using token in custom header (like X-AUTH-TOKEN)
  6. Server validates token and responds with data if everything is ok
  7. If token is not valid server responds with 401, then continue from step 3
  8. Every request to your server uses the same token

If you want to go deeper into details, feel free to ask more questions!

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top