I'm doing a token-based authentication, and I don't know how I am supposed to use authenticate directive in my route:

I'm getting access_token from a header.

post {
  headerValueByName("Access_Token") {
    access_token => {
      authenticate(??????){
        user => {
          ......
          ......
       }
      }
    }
  }
}

How can I authenticate?

有帮助吗?

解决方案

There are several ways how to do this, you can do this with some libraries like flavian proposed or do it yourself. Authenticate directives doesn't do much, i just "executes" standard authenticated mechanisms provided with Spray, you can read about them here. If this is not what you want or didn't understand how to do this, here is a small example.

Let's imagine the easiest case with token authentication, your token is saved in some storage and to authenticate a user you want just compare them. So we have this function:

def validate(token: AuthToken): Future[Authentication[User]] = {
  torage.findUserByToken(token) match { 
    case Some(user) => Right(user)
    case None => Left(AuthenticationFailedRejection(..))
  }
}

Where Authentication[User] is Either[Rejection, T]

If you take a look at authenticate directive, it's implemented with a Magnet pattern and requires AuthMagnet and you have everything to get it, cause it has a conversion:

implicit def fromFutureAuth[T](auth: ⇒ Future[Authentication[T]])(implicit executor: ExecutionContext): AuthMagnet[T] =
    new AuthMagnet(onSuccess(auth))

So now you can use it:

post {
  headerValueByName("Access_Token") { access_token => {
    authenticate(validate(access_token)) { user => {
      ......
      ......
    }
  }
}

BTW, if you are looking for a good & secure way to store user account, check stormpath, it's quite easy to integrate them with Spray api.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top