首页 文章

如何在iOS上获取Cognito用户池“sub”属性

提问于
浏览
1

我使用“Cognito用户池授权程序”(没有“AWS_IAM”选项,没有自定义编码授权程序)通过API网关调用Lambda方法并识别登录iOS客户端的用户 .

在Lambda上,我使用通过 event.requestContext.authorizer.claims.sub 从Cognito用户池授权程序获取的用户ID(用于存储具有一些DynamoDB项目的用户ID) .

我现在需要将其与iOS客户端中登录用户的id进行比较 .

我发现了 [AWSIdentityManager defaultIdentityManager].identityId ,但是(显然)返回了他 IdentityID (我可以在Cognito中的AWS控制台中查找 - >联合身份 - >身份浏览器),_我是在Cognito中看到的 - >用户池 - >用户和团体

我可以通过AWS iOS SDK获取“sub”吗?

如果我无法得到它,我应该使用哪个其他id参数,我可以在Lambda和客户端检索两者以识别当前客户端用户/发出API请求的用户?

2 回答

  • 2

    另一个解决方案(使用AWS JavaScript SDK测试):

    当我们使用Cognito进行身份验证时,我们可以检索JWT令牌:

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

    碰巧这个JWT令牌是可以解码的标准对象 .

    使用Auth0 JWT decode(npm install jwt-decode),我们可以解码此令牌并检索所有用户属性(电子邮件,用户名等)和 sub .

    var jwtDecode = require('jwt-decode');
    var decoded = jwtDecode(token);
    console.log(decoded);
    
    // prints sub, email, username, ...
    
  • 1

    似乎我必须通过用户详细信息专门请求属性,如下所示:

    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);
        }
    }];
    

相关问题