objective c如何使用refresh Token刷新Access Token



我正在使用Cognito用户池对系统中的用户进行身份验证。一个成功的身份验证会产生一个ID令牌(JWT(,访问令牌(JWT(。每一小时会产生一次TokenExpiration。我的问题是,一旦我的访问令牌过期,我如何使用存储的刷新令牌再次刷新我的访问代币?这是我的密码。

- (void)loginAWSMethod {
NSString *emailId = @"the email";
NSString *pwdTxt = @"the password";
NSLog(@"entered the login method %@ %@",emailId,pwdTxt);
AWSCognitoIdentityUser *user = [pool getUser:emailId];
[[user getSession:emailId password:pwdTxt validationData:nil]
continueWithBlock:^id _Nullable(AWSTask<AWSCognitoIdentityUserSession *> * _Nonnull task)
{
if (task.error) {
dispatch_async(dispatch_get_main_queue(), ^{
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"ERROR CATCHED++++++");
UIAlertController * alert = [UIAlertController
alertControllerWithTitle:@"Incorrect email or password."
message:@""
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* yesButton = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action)
{
}];
[alert addAction:yesButton];
[self presentViewController:alert animated:YES completion:nil];
});
[self removeWaitingProgress];
});
}else{
NSLog(@"the result is %@",task.result);
AWSCognitoIdentityUserSession *response1 = task.result;
token = response1.accessToken.tokenString;
NSLog(@"the token is %@",token);
[[user getDetails] continueWithSuccessBlock:^id _Nullable(AWSTask<AWSCognitoIdentityUserGetDetailsResponse *> * _Nonnull task) {
AWSCognitoIdentityUserGetDetailsResponse *response = task.result;
for (AWSCognitoIdentityUserAttributeType *attribute in response.userAttributes) {
//print the user attributes
NSLog(@"Attribute: %@ Value: %@", attribute.name, attribute.value);
if([attribute.name isEqualToString:@"sub"]){
cognitoID = attribute.value;
}
[defaults setValue:token forKey:@"token"];
[defaults setValue:@"yes" forKey:@"isLoggedIn"];
[defaults synchronize];
dispatch_async(dispatch_get_main_queue(), ^{
[self removeWaitingProgress];
[self gotoDashborad];
});
}
return nil;
}];
}
return  nil;
}];
}

您应该能够简单地调用-[AWSCognitoIdentityUser getSession],它将在后台返回当前有效的访问令牌,或者将刷新令牌交换为新的访问令牌:

-(nullable NSString *)accessTokenStringForCurrentUser {
AWSCognitoIdentityUser *currentUser = [pool currentUser];
__block NSString *tokenString;
// `getSession` automatically exchanges the refresh token for a valid access token if needed
[[[currentUser getSession] continueWithBlock:^id _Nullable(AWSTask<AWSCognitoIdentityUserSession *> * _Nonnull task) {
// (Error handling not shown)
if (task.result) {
AWSCognitoIdentityUserSessionToken *accessToken = task.result.accessToken;
tokenString = accessToken.tokenString;
}
return nil;
}] waitUntilFinished];
return tokenString;
}

你可能还想看看Cognito UserPools示例应用程序,它有使用UserPools的Objective C示例。

最新更新