简体   繁体   中英

akka http authentication using header token and external resources

I am trying to implement custom directives in Akka HTTP to do token based authorization and using external resources to validate the token.

I need to extract a token value from the header, and then use an external web service to validate the token to a user, and then look up the user in ldap.However, so fare I keep getting issues wrapping all this in a custom directive. I need to extract the actor system and use it in my HTTP request, but I fail in Unmarshalling the response, and in general i think i mess around in the Directive features of akka HTTP. I am searching advice on how to wrap all the external look up inside directives.

So fare i have this:

/**
 * General directive for authentication
 */
def authenticateWithHeader: Directive1[AuthenticatedUser] =
    optionalHeaderValueByName("authToken").flatMap {
      case Some(jwt) => {
        isTokenValid(jwt) match {
          case Left(user)       => provide(user)
          case Right(rejection) => reject(rejection)
        }
      }
      case _         => reject(AuthenticationFailedRejection(CredentialsMissing, HttpChallenge("schema", "realm")))
    }

And then I am trying to do the validation logic inside this:

case class TokenUser(userType: String, userName: String)

private def getUserFromToken(token: String): Directive1[AuthenticatedUser] = {
    extractActorSystem { actorSystem =>
      onSuccess(Http(actorSystem).singleRequest(HttpRequest(uri = "https://myauthservice/auth").addHeader(RawHeader("token", token)))) { value =>
        onComplete(Unmarshal(value.entity).to[TokenUser]) {
          case Success(tokenUser) => {
            // TODO: Ldap search
          }
          case Failure(exception) => {
            logger.error(exception)
          }
        }
    }}
  }

Have a look at here , it might help!

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