【问题标题】:AWS Forgot password: Unable to verify secret hash for client for iOSAWS 忘记密码:无法验证 iOS 客户端的秘密哈希
【发布时间】:2018-05-05 16:18:15
【问题描述】:

iOS 解决方案

向 aws cognito 身份池提交忘记密码请求时,该请求必须使用客户端密码以及忘记密码请求中提交的用户名进行签名。

我们如何在 swift 中以 aws 要求的格式从客户端密码和用户名创建“secretHash”?

【问题讨论】:

    标签: ios swift amazon-web-services aws-cognito aws-mobilehub


    【解决方案1】:

    此功能未记录在案,仅在某些 AWS 库的测试中发现。此代码用作提交忘记密码请求的示例,直到该功能在 AWSCongitoIdentityUserPool 库中得到更好的支持。

    Swift 3.2

    func forgotPassword(username: String) {
       let pool = AWSCognitoIdentityUserPool.default()
    
       let request = AWSCognitoIdentityProviderForgotPasswordRequest()
       request?.username = username
       request?.clientId = pool.userPoolConfiguration.clientId
       request?.secretHash = pool.calculateSecretHash(username: username)
    
       AWSCognitoIdentityProvider.default().forgotPassword(request!) { (response, error) in
           if let error = error {
               print(error)
           }
           else {
               print("success")
           }
        }
    }
    

    使用来自用户池的客户端密码对用户名进行签名。

    extension AWSCognitoIdentityUserPool {
        func calculateSecretHash(username: String) -> String? {
            guard let clientSecret = userPoolConfiguration.clientSecret else {
                return nil
            }
            guard let key = clientSecret.data(using: String.Encoding.ascii) else {
                return nil
            }
            guard let data = (username + userPoolConfiguration.clientId).data(using: String.Encoding.utf8) else {
                return nil
            }
    
            let hmac = sign256(data: data, key: key)
            return hmac.base64EncodedString()
        }
    
        fileprivate func sign256(data: Data, key: Data) -> Data {
            let algorithm: CCHmacAlgorithm = CCHmacAlgorithm(kCCHmacAlgSHA256)
            let digestLength =  Int(CC_SHA256_DIGEST_LENGTH)
            let signature = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLength)
            defer { signature.deallocate(capacity: digestLength) }
    
            data.withUnsafeBytes { dataBytes in
                key.withUnsafeBytes { keyBytes in
                    CCHmac(algorithm, keyBytes, key.count, dataBytes, data.count, signature)
                }
            }
    
            return Data(bytes: signature, count: digestLength)
        }
    
    }
    

    【讨论】:

    • 这似乎仍然是 2018 年 11 月的正确答案。感谢您的工作
    猜你喜欢
    • 2017-09-25
    • 2020-12-11
    • 2019-02-28
    • 2019-06-23
    • 2019-03-03
    • 2016-09-23
    • 2019-04-21
    • 1970-01-01
    • 2021-01-01
    相关资源
    最近更新 更多