首页 > 解决方案 > 如何从 AWS cognito 获取 awstoken

问题描述

我想在成功函数之外使用 accessToken 变量。我尝试了不同的方法来使用变量,但没有奏效。

var authenticationData = {
  Username : 'username',
  Password : 'password',
};
var authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(authenticationData);
var poolData = { UserPoolId : 'us-east-1_ExaMPle',
  ClientId : '1example23456789'
};
var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
var userData = {
  Username : 'username',
  Pool : userPool
};
var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
  onSuccess: function (result) {
    var accessToken = result.getAccessToken().getJwtToken();

    /* Use the idToken for Logins Map when Federating User Pools with identity pools or when passing through an Authorization Header to an API Gateway Authorizer */
    var idToken = result.idToken.jwtToken;
  },

  onFailure: function(err) {
    alert(err);
  },
});

标签: javascriptamazon-web-servicesamazon-cognito

解决方案


为什么不添加accessTokenauthenticationData对象?

var authenticationData = {
  Username : 'username',
  Password : 'password',
  AccessToken : ''
};

// And then set the token in the success method:
authenticationData.AccessToken = result.getAccessToken().getJwtToken();

authenticationData.AccessToken设置后,您可以在范围内的任何位置使用该值。


推荐阅读