How to get Cognito user pool “sub” attribute on iOS

浪子不回头ぞ 提交于 2019-12-06 09:33:56

Another solution (tested with the AWS JavaScript SDK):

When we authenticate with Cognito, we can retrieve a JWT token:

user.authenticateUser(authenticationDetails, {
    onSuccess: (result) => resolve(result.getIdToken().getJwtToken()),
    onFailure: (err) => reject(err)
})

It happens that this JWT token is an standard object that can be decoded.

Using Auth0 JWT decode (npm install jwt-decode), we can decode this token and retrieve all user attributes (e-mail, username, etc.) and the sub.

var jwtDecode = require('jwt-decode');
var decoded = jwtDecode(token);
console.log(decoded);

// prints sub, email, username, ...

It seems that I have to specifically request the attributes via the user details like this:

AWSCognitoIdentityUserPool *pool = [AWSCognitoIdentityUserPool CognitoIdentityUserPoolForKey:AWSCognitoUserPoolsSignInProviderKey];
AWSCognitoIdentityUser *user = [pool currentUser];

NSString *mySub;

[[user getDetails] continueWithBlock:^id _Nullable(AWSTask<AWSCognitoIdentityUserGetDetailsResponse *> * _Nonnull task) {
    if(!task.error){
        AWSCognitoIdentityUserGetDetailsResponse *response = task.result;
        NSArray<AWSCognitoIdentityProviderAttributeType*> *userAttributes = response.userAttributes;
        for (AWSCognitoIdentityProviderAttributeType *attr in self.userAttributes) {
            if ([attr.name isEqualToString:@"sub"]) {
                mySub = attr.value;
            }
        }
    } else {
        NSLog(@"Error fetching Cognito User Attributes: %@", task.error.localizedDescription);
    }
}];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!