如何使用 Akka HTTP 进行身份验证

How to do authentication using Akka HTTP

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

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

The documentation 概述了一种方法,但是省略了执行实际身份验证的相关部分...

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

在哪里可以找到此类验证器的示例实现?我已经有了用于对给定用户名和密码的用户进行身份验证的逻辑,但我无法弄清楚的是如何从 HTTP 请求(或 RequestContext)中获取 username/password(或包含两者的令牌)。

Authenticator 只是一个函数 UserCredentials => Option[T],其中 UserCredentials in case of being (check with pattern matching) Provided 具有您需要安全调用的 verifySecret(secret) 方法和 return 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 是您的自定义函数,它获取用户名和 return 您的秘密(例如密码),可能从数据库中获取。 verifySecret 将安全地比较(避免定时攻击)提供的密码与您来自 myGetSecret 的密码。通常,"secret" 是任何隐藏信息(如凭据或令牌的哈希值),但在基本身份验证的情况下,它只是从 http headers.

中提取的普通密码

如果您需要更多自定义方法 - 使用获取 HttpCredentials 作为输入的 authenticateOrRejectWithChallenge,这样您就可以从那里提取提供的密码。

有关授权的更多信息是 in scaladocs