I've incorporated the AWS Mobile Hub Cognito Sign-In as described in Add AWS Mobile User SignIn for iOS Swift and it's working as expected, however I can't seem to find a way to get the logged-in user's access_token, or more specifically, the user's sub from the decrypted access_token.
I was able to achieve this for Android by implementing a callback for AuthHandler, which calls a method called onSuccess
and passes it an AuthUserSession
object, which contains the auth_token.
From the docs, it appears there is something similar for iOS by implementing AWSSignInDelegate
, but I can't figure out if the access_token is present or not in any of the delegate method's parameters. Maybe someone more familiar with it (or the debugger) can fill in the blanks?
class AppDelegate: UIResponder, UIApplicationDelegate, AWSSignInDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
AWSSignInManager.sharedInstance().delegate = self
return AWSMobileClient.sharedInstance().interceptApplication(application, didFinishLaunchingWithOptions: launchOptions)
}
...
func onLogin(signInProvider: AWSSignInProvider, result: Any?, error: Error?) {
// How to find the auth_token or sub from here?
}
}
The onLogin
method's result
parameter seems like it's the most likely candidate for having what I need, but I can't figure out how to access it. If there's any other way of getting it, I'd be open to that too.
You can use the AWSCognitoUserPoolsSignInProvider
singleton object to get the Cognito User object and then you can go over the attributes to get the user-sub attribute.
AWSCognitoIdentityUser *user = [[[AWSCognitoUserPoolsSignInProvider sharedInstance] getUserPool] 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);
}
}];