身份验证后的AWS Cognito getCurrentUser()没有刷新

时间:2016-10-05 16:03:30

标签: amazon-web-services amazon-cognito

我尝试在身份验证后立即更新用户的属性。 Auth工作正常,我可以用它检索用户属性。 但问题是var cognitoUser = getUserPool().getCurrentUser();返回null。如何检索当前用户以便我能够更新属性但不刷新浏览器?

也许另一个问题是,如何在不刷新浏览器的情况下使用accessToken在当前用户上运行函数?

var cognitoUser = getUserPool().getCurrentUser();
  if (cognitoUser != null) {
    cognitoUser.getSession(function(err, session) {
      if ( err ) {
        console.log(err);
        return;
      }else if( session.isValid() ){
        updateUserAttribute( cognitoUser, 'custom:attr', attr )
      }
    });

  }else{
    console.log('Cognito User is null');
    return;
  }

3 个答案:

答案 0 :(得分:0)

var cognitoUser = getUserPool().getCurrentUser();

如果正确初始化用户池,则应该返回最后一个经过身份验证的用户。验证成功后,我们将键入客户端ID的用户保存到本地存储。无论何时调用getCurrentUser,它都将从本地存储中检索该特定的最后一个经过身份验证的用户。令牌是键入该用户和客户端ID。成功进行身份验证后,它们也会保存到本地存储中。访问访问令牌应该只是:

cognitoUser.getSignInUserSession().getAccessToken().getJwtToken())

您可以将令牌直接用于CognitoIdentityServiceProvider客户端中公开的操作。

答案 1 :(得分:0)

这是一个相当古老的问题,所以您现在可能已经开始了,但我认为您需要使用userpoolId和clientID创建用户池。我不认为你可以调用getUserPool()而不知道那些在内存中已知和/或以某种方式可用的内容。例如:

function makeUserPool () {
    var poolData = {
        UserPoolId : "your user pool id here",
        ClientId : "you client id here"
    };
    return new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData);
}
var userPool = makeUserPool();
var currAWSUser = userPool.getCurrentUser();

答案 2 :(得分:0)

getUserPool()。getCurrentUser()在本地存储上查找用户,如果返回null则是因为本地存储尚未设置用户。

要在本地存储上设置用户,我使用一个CognitoAuth实例来完成这项工作。

此解决方案使用的是Cognito托管UI。 在Cognito用户界面返回的回调网址上:

        import {CognitoAuth} from 'amazon-cognito-auth-js';

        var authData = {
        UserPoolId: 'us-east-1_xxxxxx',
        ClientId: 'xxxxxxx',
        RedirectUriSignIn : 'https://examole.com/login',
        RedirectUriSignOut : 'https://example.com/logout',
        AppWebDomain : 'example.com',
        TokenScopesArray: ['email']
        };
        var auth = new CognitoAuth(authData);
        auth.userhandler = {
        onSuccess: function(result) {
          //you can do something here
        },
        onFailure: function(err) {
            // do somethig if fail
        }
    };

    //get the current URL with the Hash that contain Cognito Tokens tokens    
    var curUrl = window.location.href;

    //This parse the hash and set the user on the local storage. 
    auth.parseCognitoWebResponse(curUrl);

然后,如果您调用getUserPool()。getCurrentUser(),则该值将不为空。

相关问题