Python AWS Cognito 如何像Javascript一样认证到其他用户池

-1 投票
0 回答
42 浏览
提问于 2025-04-12 00:48

我对AWS Cognito的经验不多。在JavaScript中,我可以用下面的代码来验证其他用户池的用户:

import dotenv from 'dotenv';
dotenv.config();
import { CognitoUserPool, CognitoUser, AuthenticationDetails } from 'amazon-cognito-identity-js';

export async function getJwtToken() {
  const UserPoolId = process.env.COGNITO_USER_POOL_ID;
  const ClientId = process.env.COGNITO_APP_CLIENT_ID;
  const Username = process.env.COGNITO_USERNAME;
  const Password = process.env.COGNITO_PASSWORD;
  const userPool = new CognitoUserPool({
    UserPoolId,
    ClientId
  });

  const cognitoUser = new CognitoUser({
    Username,
    Pool: userPool
  });

  const authenticationDetails = new AuthenticationDetails({
    Username,
    Password
  });

  return new Promise((resolve) => {
    cognitoUser.authenticateUser(authenticationDetails, {
      onSuccess: function (result) {
        const token = result.getIdToken().getJwtToken();
        resolve(token);
      },
      onFailure: function (err) {
        console.error('Error obtaining JWT token:', err);
        resolve(null);
      }
    });
  });
}

但是在Python中,我需要用到cognito_idp_client来进行验证。我参考了这个代码,GitHub链接

def start_sign_in(self, user_name, password):
    """
    Starts the sign-in process for a user by using administrator credentials.
    This method of signing in is appropriate for code running on a secure server.

    If the user pool is configured to require MFA and this is the first sign-in
    for the user, Amazon Cognito returns a challenge response to set up an
    MFA application. When this occurs, this function gets an MFA secret from
    Amazon Cognito and returns it to the caller.

    :param user_name: The name of the user to sign in.
    :param password: The user's password.
    :return: The result of the sign-in attempt. When sign-in is successful, this
             returns an access token that can be used to get AWS credentials. Otherwise,
             Amazon Cognito returns a challenge to set up an MFA application,
             or a challenge to enter an MFA code from a registered MFA application.
    """
    try:
        kwargs = {
            "UserPoolId": self.user_pool_id,
            "ClientId": self.client_id,
            "AuthFlow": "ADMIN_USER_PASSWORD_AUTH",
            "AuthParameters": {"USERNAME": user_name, "PASSWORD": password},
        }
        if self.client_secret is not None:
            kwargs["AuthParameters"]["SECRET_HASH"] = self._secret_hash(user_name)
        response = self.cognito_idp_client.admin_initiate_auth(**kwargs)
        challenge_name = response.get("ChallengeName", None)
        if challenge_name == "MFA_SETUP":
            if (
                "SOFTWARE_TOKEN_MFA"
                in response["ChallengeParameters"]["MFAS_CAN_SETUP"]
            ):
                response.update(self.get_mfa_secret(response["Session"]))
            else:
                raise RuntimeError(
                    "The user pool requires MFA setup, but the user pool is not "
                    "configured for TOTP MFA. This example requires TOTP MFA."
                )
    except ClientError as err:
        logger.error(
            "Couldn't start sign in for %s. Here's why: %s: %s",
            user_name,
            err.response["Error"]["Code"],
            err.response["Error"]["Message"],
        )
        raise
    else:
        response.pop("ResponseMetadata", None)
        return response

没有cognito_idp_client,Python的验证就无法工作。我可以用下面的代码创建自己的cognito_idp_client

cognito_client = boto3.client(
'cognito-idp',
aws_access_key_id=os.environ.get('AWS_ACCESS_KEY'),
aws_secret_access_key=os.environ.get('AWS_SECRET_KEY'),
region_name=os.environ.get('AWS_REGION'),

)

但是这样做不行,因为user_pool_id不是我的AWS Cognito。有没有办法像在JavaScript中那样,验证其他服务的用户池呢?

0 个回答

暂无回答

撰写回答