简体   繁体   中英

Reaching JWT Token in play2 silhouette JWTAuthenticator

Play-silhouette-rest activator template gives a good example how to use REST authentication/sign up with HeaderAuthenticator. Getting sign in request it creates user and returns token in both response body and header

 val response = Ok(Json.toJson(Token(token = authenticator.id, expiresOn = authenticator.expirationDate)))
 env.authenticatorService.init(authenticator, Future.successful(response))

In this example I am getting same tokens in body (being initialized on first line) and in headers (being initialized on second line).

Willing to use JWTAuthenticator, I changed code to use this instead (code is the same, only one difference is dependency injection code) so I expected the same appearance.

But with JWTAuthenticator authenticator.id gives me some another generated ID (based on which real JSON Web Token is generated later) and JSON Web Token is being written only in header, on second code line.

I am willing to return real json web token in reponse body but don't want to read headers after I wrote in them in the same method.

Is there any solution?

The only solution I see is to init the authenticator with the request instead of the response. This is possible because the authenticator service contains two init methods. The first can init the authenticator with the response and the second can init the authenticator with the request.

env.authenticatorService.init(authenticator, request).map { r =>
  r.headers.get("X-Auth-Token") match {
    case Some(token) => Ok(Json.toJson(Token(token = token, expiresOn = authenticator.expirationDate)))
    case None => BadRequest("Couldn't generate token")
  }
}

I'll see if I can add an additional init method which initializes the authenticator and returns the generated value. You can follow this issue .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM