AWS cognito:注册确认后自动登录

问题描述 投票:0回答:1

我正在使用 AWS Cognito 的 JavaScript SDK (http://docs.aws.amazon.com/cognito/latest/developerguide/using-amazon-cognito-user-identity-pools-javascript-examples.html)。

当新用户完成注册确认后,文档说用户现在可以登录了。此时是否可以自动登录用户?

例如,在确认后,当我使用以下内容时,我得到 null:

userPool.getCurrentUser(); 

如果这是预期的行为,是否有任何方法可以在不再次明确询问用户的情况下登录用户?

我知道这不是一个好主意,我能想到的一件事是将用户凭据保存在本地存储中,并在确认后使用它们自动登录。还有比这更好的想法吗?

amazon-cognito
1个回答
2
投票

用户注册后,您的后端将接收用户凭据,您可以使用该凭据生成 JWT 令牌。然后,您可以在同一响应中添加 JWT 令牌,浏览器客户端可以使用该令牌来请求授权端点。

示例:

     AWSCognito.config.region = 'us-east-1'; //This is required to derive the endpoint
    
     var poolData = {
         UserPoolId: 'us-east-1_TcoKGbf7n',
         ClientId: '4pe2usejqcdmhi0a25jp4b5sh3'
     };
     var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData);
     var attributeList = [];
     var dataEmail = {
         Name: 'email',
         Value: '[email protected]'
     };
     var authenticationData = {
         Username: 'username',
         Password: 'password',
     };
     var attributeEmail = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserAttribute(dataEmail);
     attributeList.push(attributeEmail);
    
     userPool.signUp(authenticationData.Username, authenticationData.Password, attributeList, null, function (err, result) {
         if (err) {
             alert(err);
             return;
         }
         var authenticationDetails = new AWSCognito.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData);
         var userData = {
             Username: authenticationData.Username,
             Pool: userPool
         };
         var cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
         cognitoUser.authenticateUser(authenticationDetails, {
             onSuccess: function (result) {
                 console.log('access token + ' + result.getAccessToken().getJwtToken());
                 /*Use the idToken for Logins Map when Federating User Pools with Cognito Identity or when passing through an Authorization Header to an API Gateway Authorizer*/
                 console.log('idToken + ' + result.idToken.jwtToken);
                 /*Return the result.idToken.jwtToken with the response*/
             },
             onFailure: function (err) {
                 alert(err);
             },
    
         });
     });
© www.soinside.com 2019 - 2024. All rights reserved.