Аутентификация AWS Cognito через Facebook прошла успешно, но getCurrentUser возвращает ноль

В браузере после входа в Facebook вызывается statusChangeCallback. Все удается. Cognito даже возвращает Identity Id. Однако userPool.getCurrentUser() возвращает значение NULL. Cognito не считает, что существует аутентифицированный пользователь. Как я могу это исправить? Благодарю.

function statusChangeCallback(response) {
    if(response.status == 'connected' && response.authResponse) {
        testAPI()

        console.log("FB statusChangeCallback", JSON.stringify(response))

        AWSCognito.config.credentials = new AWSCognito.CognitoIdentityCredentials({
            IdentityPoolId : '<%=process.env.AWS_USERPOOLGUID%>', // your identity pool id here
            Logins : {
                'graph.facebook.com': response.authResponse.accessToken
            }
        });
        console.log(JSON.stringify(AWSCognito.config.credentials))


        AWSCognito.config.region = '<%= process.env.AWS_REGION%>'

        AWSCognito.config.credentials.refresh(function(error) {
            if (error) {
                console.error("AWSCognito.config.credentials.get", error);
            } else {
                console.log("Cognito Identity Id", AWSCognito.config.credentials.identityId);
                console.log('Successfully logged!');
                var cognitoUser = userPool.getCurrentUser();
                console.log('cognitoUser', cognitoUser);

            }
        });
    }
}

2 ответа

userPool.getCurrentUser();

относится к аутентифицированному пользователю в отношении определенного пула пользователей. В приведенном выше коде вы получаете учетные данные AWS с использованием идентификатора Facebook. Однако текущий пользователь ссылается на последнего аутентифицированного пользователя пула пользователей. Это сохраняется в локальном хранилище после успешной аутентификации. Таким образом, вам нужно будет сначала пройти аутентификацию, как показано ниже.

var authenticationData = {
    Username : 'username',
    Password : 'password',
};
var authenticationDetails = new AWSCognito.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData);
var poolData = { 
    UserPoolId : '...', // Your user pool id here
    ClientId : '...' // Your client id here
};
var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData);
var userData = {
    Username : 'username',
    Pool : userPool
};
var cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
    onSuccess: function (result) {
        console.log('access token + ' + result.getAccessToken().getJwtToken());

        AWS.config.credentials = new AWS.CognitoIdentityCredentials({
            IdentityPoolId : '...', // your identity pool id here
            Logins : {
                // Change the key below according to the specific region your user pool is in.
                'cognito-idp.<region>.amazonaws.com/<YOUR_USER_POOL_ID>' : result.getIdToken().getJwtToken()
            }
        });

        // Instantiate aws sdk service objects now that the credentials have been updated.
        // example: var s3 = new AWS.S3();

    },

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

});

Похоже, вам нужно изменить свой AWSCognito.config.credentials с того, что у вас есть на это:

// Add the Facebook access token to the Cognito credentials login map.
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
  IdentityPoolId: 'IDENTITY_POOL_ID',
  Logins: {
    'graph.facebook.com': response.authResponse.accessToken
  }
});

// Obtain AWS credentials
AWS.config.credentials.get(function(){
    // Access AWS resources here.
});

ВНИМАНИЕ: IdentityPoolId: 'IDENTITY_POOL_ID', а не IdentityPoolId: '<% = process.env.AWS_USERPOOLGUID%>', // ваш идентификатор пула идентификаций здесь

Похоже, вы пытаетесь получить доступ к вашему ПОЛЬЗОВАТЕЛЬСКОМУ БАССЕЙНУ, а не к вашему IDENTITY POOL.

Пользователи Facebook живут в Identity Pool, потому что они являются федеративными пользователями с сервера Facebook.

Другие вопросы по тегам