使用 soto-cognito-authentication-kit

问题描述

我需要使用 AWS Cognito 实施本机身份验证,并且我正在尝试在我的 iOS 应用程序(客户端)中使用 https://github.com/adam-fowler/soto-cognito-authentication-kit

我正在努力使用 CognitoAuthenticatable 对象来启动用户名/密码身份验证。

这是我的代码

class LoginHandler {
    func handleLogin(username: String,password: String) {
        var eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)

        let data = AWSCognitoContext()
        let response = self.authenticatable.authenticate(
            username: username,password: password,requireAuthenticatedClient: false,clientMetadata: nil,context: data,on: eventLoopGroup.next()
        )

        response.flatMap { response in
            // use response object
        }
    }
}

class AWSCognitoContext: CognitoContextData {
    var contextData: CognitoIdentityProvider.ContextDataType? {
        return CognitoIdentityProvider.ContextDataType(
            httpHeaders: [],ipAddress: "",serverName: "",serverPath: "")
    }
}

authenticate 方法应该返回 EventLoopFuture<CognitoAuthenticateResponse>

  1. 如何处理 authenticate 方法的响应?我收到错误 Generic parameter 'NewValue' Could not be inferred
  2. 如何构造 CognitoContextData 对象。我只想使用 AWS 服务器位置的认值。

解决方法

authenticate 函数立即返回 EventLoopFuture<...>。它会在稍后完成,并在完成时使用身份验证的结果。 EventLoopFuture 对象有多种方法来处理此结果。最简单的是whenComplete。您可以执行以下操作

response.whenComplete { result in
    switch result {
    case .failure(let error):
        process error ...
    case .success(let response):
        process authenticate response
    }
}

如果要处理响应对象,可以使用 map。例如

response.map { response -> NextObject in
    return CreateNextObject(from: response)
}

如果要将多个 flatMap 链接在一起,可以使用 EventLoopFutures。例如

response.flatMap { response -> EventLoopFuture<NextObject> in
    return CreateEventLoopFutureNextObject(from: response)
}

如果您遇到 could not be inferred 错误的问题,最好明确说明您的闭包返回的内容。

swift nio 文档将为您提供更多信息 https://apple.github.io/swift-nio/docs/current/NIO/Classes/EventLoopFuture.html

上下文数据将向 Cognito 提供此身份验证请求来自何处的上下文。当 requireAuthenticatedClient 为 false 时,这并不真正使用。所以提供一个空的上下文是可以的。

您不应该在函数中创建 EventLoopGroup 的另一件事。它正在创建可能耗时的线程,然后您必须在所有进程完成后关闭它们。您可以在此处使用 eventLoopGroup authenticatable.configuration.cognitoIDP.eventLoopGroup

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...