如何使用 Python 对 AWS Cognito 用户池进行身份验证?

Cer*_*rin 3 python amazon-web-services amazon-cognito

我有一个静态无服务器网站,允许使用AWS Cognito 用户池通过 Javascript 进行身份验证。

现在我正在尝试启用一些编程访问,因此我需要通过 Python 脚本进行相同的身份验证。这可能吗?该文档没有提供任何Python代码示例。

我只是想找到某种方法让 Python 针对 AWS URL 发出 GET 或 POST 请求,向其传递用户名和登录信息,然后取回验证身份验证的签名 cookie

我发现的最接近的例子是这段代码,它引用了cognito-idp API。我修改为:

import boto3
client_id = '<my_app_client_id>'
region_name = 'us-east-1'
auth_data = { 'USERNAME':'myusername' , 'PASSWORD':'mypassword' }
provider_client = boto3.client('cognito-idp', region_name=region_name)
resp = provider_client.initiate_auth(AuthFlow='USER_PASSWORD_AUTH', AuthParameters=auth_data, ClientId=client_id)
print('resp:', resp)
Run Code Online (Sandbox Code Playgroud)

但是,即使我使用与 Javascript API 相同的凭据,也无法进行身份验证并仅返回错误:

botocore.exceptions.NoCredentialsError: Unable to locate credentials
Run Code Online (Sandbox Code Playgroud)

这是与 Javascript Cognito API 等效的正确 Python 吗?

inf*_*ith 8

以下代码片段显示了使用 boto3 的 Cognito 的完整身份验证工作流程。

def get_secret_hash(username):
    msg = username + CLIENT_ID
    dig = hmac.new(
        str(CLIENT_SECRET).encode('utf-8'),
        msg=str(msg).encode('utf-8'),
        digestmod=hashlib.sha256
    ).digest()
    d2 = base64.b64encode(dig).decode()
    return d2

def initiate_auth(client, username, password):
    secret_hash = get_secret_hash(username)
    try:
        resp = client.admin_initiate_auth(
            UserPoolId=USER_POOL_ID,
            ClientId=CLIENT_ID,
            AuthFlow='ADMIN_NO_SRP_AUTH',
            AuthParameters={
                'USERNAME': username,
                'SECRET_HASH': secret_hash,
                'PASSWORD': password,
            },
            ClientMetadata={
                'username': username,
                'password': password, })
    except client.exceptions.NotAuthorizedException:
        return None, "The username or password is incorrect"
    except client.exceptions.UserNotConfirmedException:
        return None, "User is not confirmed"
    except Exception as e:
        return None, e.__str__()
    return resp, None

@app.route('/auth/login', methods=['POST'])
def login():
    event = auth.current_request.json_body
    client = boto3.client('cognito-idp')
    username = event['username']
    password = event['password']
    for field in ["username", "password"]:
        if event.get(field) is None:
            return {"error": True,
                    "success": False,
                    "message": f"{field} is required",
                    "data": None}
    resp, msg = initiate_auth(client, username, password)
    if msg != None:
        return {'message': msg,
                "error": True, "success": False, "data": None}
    if resp.get("AuthenticationResult"):
        return {'message': "success",
                "error": False,
                "success": True,
                "data": {
                    "id_token": resp["AuthenticationResult"]["IdToken"],
                    "refresh_token": resp["AuthenticationResult"]["RefreshToken"],
                    "access_token": resp["AuthenticationResult"]["AccessToken"],
                    "expires_in": resp["AuthenticationResult"]["ExpiresIn"],
                    "token_type": resp["AuthenticationResult"]["TokenType"]
                }}
    else:  # this code block is relevant only when MFA is enabled
        return {"error": True,
                "success": False,
                "data": None, "message": None}

Run Code Online (Sandbox Code Playgroud)

这是从函数中解析出的重要部分。

       resp = client.admin_initiate_auth(
            UserPoolId=USER_POOL_ID,
            ClientId=CLIENT_ID,
            AuthFlow='ADMIN_NO_SRP_AUTH',
            AuthParameters={
                'USERNAME': username,
                'SECRET_HASH': secret_hash,
                'PASSWORD': password,
            },
            ClientMetadata={
                'username': username,
                'password': password, })
Run Code Online (Sandbox Code Playgroud)

这些示例取自由四部分组成的教程,遗憾的是,该教程无法帮助我将其与 Chalice CognitoUserPoolAuthorizer 集成,但在其他方面似乎运行良好。如果您找不到更好的代码示例,请参阅以下教程。