15

寻找有关如何使用 akka HTTP 进行身份验证的良好解释。给定一条看起来像的路线

val route = 
  path("account") {
    authenticateBasic(realm = "some realm", myAuthenticator) { user =>
      get {
        encodeResponseWith(Deflate) {
          complete {
            //do something here
          }
        }
      }
    }
  }

该文档概述了一种方法,但随后省略了执行实际身份验证的相关部分......

// backend entry points
def myAuthenticator: Authenticator[User] = ???

我在哪里可以找到这种身份验证器的示例实现?我已经有了对给定用户名和密码的用户进行身份验证的逻辑,但我不知道如何从 HTTP 请求(或 RequestContext)中获取用户名/密码(或包含两者的令牌)。

4

1 回答 1

11

Authenticator 只是一个函数UserCredentials => Option[T],如果UserCredentials存在(检查模式匹配)ProvidedverifySecret(secret)方法,您需要Some在成功的情况下安全调用并返回(例如某些用户),例如:

def myAuthenticator: Authenticator[User] = {
  case p@Provided(username) =>
    if(p.verifySecret(myGetSecret(username))) Some(username) else None
  case Missing => None //you can throw an exeption here to get customized response otherwise it will be regular `CredentialsMissing` message

}   

myGetSecret是您的自定义函数,它获取用户名并返回您的秘密(例如密码),可能从数据库中获取。verifySecret将安全地将提供的密码与您的密码进行比较(以避免时间攻击)myGetSecret。通常,“秘密”是任何隐藏信息(如凭据或令牌的哈希),但在基本身份验证的情况下,它只是从 http 标头中提取的普通密码。

如果您需要更多自定义方法 - 使用authenticateOrRejectWithChallengeHttpCredentials作为输入,因此您可以从那里提取提供的密码。

有关授权的更多信息在 scaladocs 中

于 2015-10-19T02:10:36.933 回答