AWS忘记密码:无法验证iOS客户端的秘密哈希值

时间:2017-11-22 02:49:00

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

iOS解决方案

当向aws cognito身份池提交忘记的密码请求时,请求必须使用客户的秘密与忘记密码请求中提交的用户名一起签名。

我们怎样才能以aws所需的格式从客户端密码和swift中的用户名创建“secretHash”?

1 个答案:

答案 0 :(得分:2)

此功能未记录,仅在某些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)
    }

}