簡體   English   中英

如何使用 boto3 為 AWS Cognito 創建 SECRET_HASH?

[英]How to create a SECRET_HASH for AWS Cognito using boto3?

我想使用 boto3 和 python 為 AWS Cognito 創建/計算 SECRET_HASH。 這將被納入我的權證叉。

我將我的 cognito 應用程序客戶端配置為使用app client secret 但是,這破壞了以下代碼。

def renew_access_token(self):
    """
    Sets a new access token on the User using the refresh token.

    NOTE:
    Does not work if "App client secret" is enabled. 'SECRET_HASH' is needed in AuthParameters.
    'SECRET_HASH' requires HMAC calculations.

    Does not work if "Device Tracking" is turned on.
    https://stackoverflow.com/a/40875783/1783439

    'DEVICE_KEY' is needed in AuthParameters. See AuthParameters section.
    https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html
    """
    refresh_response = self.client.initiate_auth(
        ClientId=self.client_id,
        AuthFlow='REFRESH_TOKEN',
        AuthParameters={
            'REFRESH_TOKEN': self.refresh_token
            # 'SECRET_HASH': How to generate this?
        },
    )

    self._set_attributes(
        refresh_response,
        {
            'access_token': refresh_response['AuthenticationResult']['AccessToken'],
            'id_token': refresh_response['AuthenticationResult']['IdToken'],
            'token_type': refresh_response['AuthenticationResult']['TokenType']
        }
    )

當我運行它時,我收到以下異常:

botocore.errorfactory.NotAuthorizedException: 
An error occurred (NotAuthorizedException) when calling the InitiateAuth operation: 
Unable to verify secret hash for client <client id echoed here>.

這個答案告訴我,使用 cognito 客戶端密碼需要 SECRET_HASH。

aws API 參考文檔AuthParameters 部分聲明如下:

對於 REFRESH_TOKEN_AUTH/REFRESH_TOKEN:USERNAME(必需)、SECRET_HASH(如果應用程序客戶端配置了客戶端密碼,則必需)、REFRESH_TOKEN(必需)、DEVICE_KEY

boto3 文檔聲明 SECRET_HASH 是

使用用戶池客戶端的密鑰和用戶名加上消息中的客戶端 ID 計算得出的密鑰散列消息身份驗證代碼 (HMAC)。

文檔解釋了需要什么,但沒有解釋如何實現這一點。

下面的get_secret_hash方法是我在 Python 中為 Cognito 用戶池實現編寫的解決方案,並帶有示例用法:

import boto3
import botocore
import hmac
import hashlib
import base64


class Cognito:
    client_id = app.config.get('AWS_CLIENT_ID')
    user_pool_id = app.config.get('AWS_USER_POOL_ID')
    identity_pool_id = app.config.get('AWS_IDENTITY_POOL_ID')
    client_secret = app.config.get('AWS_APP_CLIENT_SECRET')
    # Public Keys used to verify tokens returned by Cognito:
    # http://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-with-identity-providers.html#amazon-cognito-identity-user-pools-using-id-and-access-tokens-in-web-api
    id_token_public_key = app.config.get('JWT_ID_TOKEN_PUB_KEY')
    access_token_public_key = app.config.get('JWT_ACCESS_TOKEN_PUB_KEY')

    def __get_client(self):
        return boto3.client('cognito-idp')

    def get_secret_hash(self, username):
        # A keyed-hash message authentication code (HMAC) calculated using
        # the secret key of a user pool client and username plus the client
        # ID in the message.
        message = username + self.client_id
        dig = hmac.new(self.client_secret, msg=message.encode('UTF-8'),
                       digestmod=hashlib.sha256).digest()
        return base64.b64encode(dig).decode()

    # REQUIRES that `ADMIN_NO_SRP_AUTH` be enabled on Client App for User Pool
    def login_user(self, username_or_alias, password):
        try:
            return self.__get_client().admin_initiate_auth(
                UserPoolId=self.user_pool_id,
                ClientId=self.client_id,
                AuthFlow='ADMIN_NO_SRP_AUTH',
                AuthParameters={
                    'USERNAME': username_or_alias,
                    'PASSWORD': password,
                    'SECRET_HASH': self.get_secret_hash(username_or_alias)
                }
            )
        except botocore.exceptions.ClientError as e:
            return e.response

當我嘗試上述解決方案時,我也遇到了 TypeError。 這是對我有用的解決方案:

import hmac
import hashlib
import base64

# Function used to calculate SecretHash value for a given client
def calculateSecretHash(client_id, client_secret, username):
    key = bytes(client_secret, 'utf-8')
    message = bytes(f'{username}{client_id}', 'utf-8')
    return base64.b64encode(hmac.new(key, message, digestmod=hashlib.sha256).digest()).decode()

# Usage example
calculateSecretHash(client_id, client_secret, username)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM