How do I access the group for a Cognito User account?

后端 未结 7 798
情话喂你
情话喂你 2020-12-14 00:54

In AWS Cognito, you can add a user to a group (after first creating a group). A user may belong to one or more groups.

With using the JavaScript SDK (https://github

7条回答
  •  北荒
    北荒 (楼主)
    2020-12-14 01:51

    I originally expected the Cognito JavaScript API to provide a simple property or method to return the list of groups, but instead I concluded that it was buried within a token, and thus had to learn about jwt. Once the Cognito User is established and the session is retrieved, the array of groups is available within the IdToken.

    var jwtDecode = require('jwt-decode');
    var AmazonCognitoIdentity = require('amazon-cognito-identity-js');
    var CognitoUserPool = AmazonCognitoIdentity.CognitoUserPool;
    var CognitoUser = AmazonCognitoIdentity.CognitoUser;
    
    var userPool = new CognitoUserPool({UserPoolId:'', ClientId:''");
    ...
    app.get('/app', function(req, res){
        var cognitoUser = userPool.getCurrentUser();
        if(cognitoUser != null){
            cognitoUser.getSession(function(err, session) {
                if (err) {
                    console.error(err);
                    return;
                }
                console.log('session validity: ' + session.isValid());
    
                var sessionIdInfo = jwtDecode(session.getIdToken().jwtToken);
                console.log(sessionIdInfo['cognito:groups']);
            });
        }
    });
    

提交回复
热议问题