如何针对 AWS Cognito 用户池进行身份验证

How do I authenticate against an AWS Cognito User Pool

本文关键字:身份验证 用户 Cognito 何针 AWS      更新时间:2023-09-26

我创建了一个Cognito用户池。 我可以列出用户并使用 Java AWS SDK 中的 AWSCognitoIdentityProviderClient 添加用户。

但是,我有一个自定义登录页面,我希望使用输入的用户名和密码,并根据我的用户池进行身份验证。 我在 Java AWS 开发工具包中看不到任何可以传递凭证并从中获取身份验证结果的地方。

编辑:我无法克服此错误:

未授权异常:配置中缺少凭据

相关代码:

    AWS.config.region = 'us-east-1';
    AWS.config.credentials = new AWS.CognitoIdentityCredentials({
        IdentityPoolId: 'us-east-1:087a3210-64f8-4dae-9e3c...' // your identity pool id here
    });
    AWSCognito.config.region = 'us-east-1';
    AWSCognito.config.credentials = new AWS.CognitoIdentityCredentials({
        IdentityPoolId: 'us-east-1:087a3210-64f8-4dae-9e3c...' // your identity pool id here
    });
    var poolData = {
        UserPoolId: 'us-east-1_39RP...',
        ClientId: 'ttsj9j5...',
        ClientSecret: 'bkvkj9r8kl2ujrlu41c7krsb6r7nub2kb260gj3mgi...'
    };
    var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData);
    var authenticationData = {
        Username: 'test@foo.com',
        Password: 'foobarfoo',
    };
    var authenticationDetails = new AWSCognito.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData);
    var userData = {
        Username: 'test@foo.com',
        Pool: userPool
    };
    var cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
    cognitoUser.authenticateUser(authenticationDetails, {
        onSuccess: function (result) {
            console.log('access token + ' + result.getAccessToken().getJwtToken());
        },
        onFailure: function (err) {
            alert(err);
        },
    });

AWS Java 开发工具包包含用于对用户池中的用户进行身份验证的 API。您可以使用 AWSCognitoIdentityProviderClient 类的 InitiateAuth api 或 AdminInitiateAuth API 对用户进行身份验证。文档中介绍了这两个 API 之间的区别。简而言之,对于 InitiateAuth,您需要执行 SRP 计算,然后将其传递给 API,而在 AdminInitiateAuth 中,您可以直接传递用户名和密码。您可以了解这两种情况下的安全隐患,并决定使用哪一种。

文档:https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-authentication-flow.html

接口参考:https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html

https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html

我的工作样本(凹槽):

def login() {
    AWSCognitoIdentityProviderClient client = new AWSCognitoIdentityProviderClient()
    println("Provider client: " + client)
    client.setRegion(Region.getRegion(Regions.AP_NORTHEAST_1))
    HashMap authParams = new HashMap<>()
    authParams.put("USERNAME", "User1")
    authParams.put("PASSWORD", "a*123")
    AdminInitiateAuthRequest adminInitiateAuthRequest = new AdminInitiateAuthRequest()
            .withClientId(<YOUR_CLIENT_ID>)
            .withUserPoolId(<YOUR_USER_POOL_ID>)
            .withAuthFlow(AuthFlowType.ADMIN_NO_SRP_AUTH )
            .withAuthParameters(authParams)
    AdminInitiateAuthResult result = client.adminInitiateAuth(adminInitiateAuthRequest);
    if (result != null) {
        System.out.println("AdminInitiateAuthResult:");
        System.out.println(result.toString());
    } else {
        System.out.println("No result available");
        return;
    }
}

目前仅通过JavaScript,iOS和Android支持身份验证。 在测试期间,进行身份验证所需的 API 不是服务器 SDK(java、python 等)的一部分。 使用 JavaScript SDK 是从登录页面进行身份验证的推荐方法。

在这里检查 https://github.com/aws/amazon-cognito-identity-js

缺少一行代码

此页面 http://docs.aws.amazon.com/cognito/latest/developerguide/using-amazon-cognito-user-identity-pools-javascript-examples.html 未更新

// Need to provide placeholder keys unless unauthorised user access is enabled for user pool
AWSCognito.config.update({accessKeyId: 'anything', secretAccessKey: 'anything'})

包含此内容后,我不再出现此错误。