如何在iOS上获取Cognito用户池“sub”属性
我使用“Cognito用户池授权程序”(没有“AWS_IAM”选项,没有自定义编码授权程序)通过API网关调用Lambda方法并识别登录iOS客户端的用户。
在Lambda上,我使用通过event.requestContext.authorizer.claims.sub
从Cognito用户池授权程序获取的用户ID(用于存储具有一些DynamoDB项目的用户ID)。
我现在需要将其与iOS客户端中登录用户的id进行比较。
我找到了[AWSIdentityManager defaultIdentityManager].identityId
,但是(显然)它返回了IdentityID (我可以在Cognito中的AWS控制台中查找 – >联合身份 – >身份浏览器), 这与“sub”id不同我在Cognito中看到 – >用户池 – >用户和组
我可以通过AWS iOS SDK获得“sub”吗?
如果我无法得到它,我应该使用哪个其他id参数,我可以在Lambda和客户端检索两者以识别当前客户端用户/发出API请求的用户?
似乎我必须通过用户详细信息专门请求属性,如下所示:
AWSCognitoIdentityUserPool *pool = [AWSCognitoIdentityUserPool CognitoIdentityUserPoolForKey:AWSCognitoUserPoolsSignInProviderKey]; AWSCognitoIdentityUser *user = [pool currentUser]; NSString *mySub; [[user getDetails] continueWithBlock:^id _Nullable(AWSTask * _Nonnull task) { if(!task.error){ AWSCognitoIdentityUserGetDetailsResponse *response = task.result; NSArray *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); } }];
另一个解决方案(使用AWS JavaScript SDK测试):
当我们使用Cognito进行身份validation时,我们可以检索JWT令牌:
user.authenticateUser(authenticationDetails, { onSuccess: (result) => resolve(result.getIdToken().getJwtToken()), onFailure: (err) => reject(err) })
碰巧这个JWT令牌是可以解码的标准对象。
使用Auth0 JWT解码 (npm install jwt-decode),我们可以解码此令牌并检索所有用户属性(电子邮件,用户名等)和sub
。
var jwtDecode = require('jwt-decode'); var decoded = jwtDecode(token); console.log(decoded); // prints sub, email, username, ...