首页 > 解决方案 > 使用 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 服务器位置的默认值。

标签: iosamazon-cognitosoto

解决方案


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/EventLoopF​​uture.html

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

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


推荐阅读