AFOAuth2Client和刷新令牌

如何在iPad应用程序中实现Oauth?

AFOAuth2Client如何pipe理oauth 2.0中的刷新令牌机制?

有没有什么方法可以在课堂上实现,还是我们必须以自己的方式来实现呢? 如何检查令牌是否过期?

我解决这个问题的方法是用一个代码块来包装所有的请求,如果需要的话,这个代码块会刷新访问令牌

为成功和失败块添加一些types定义:

typedef void (^YFRailsSaasApiClientSuccess)(AFJSONRequestOperation *operation, id responseObject); typedef void (^YFRailsSaasApiClientFailure)(AFJSONRequestOperation *operation, NSError *error); 

那么请求方法是:

 - (void)getProductsWithSuccess:(YFRailsSaasApiClientSuccess)success failure:(YFRailsSaasApiClientFailure)failure { NSLog(@"getProductsWithSuccess"); success = ^(AFJSONRequestOperation *operation, id responseObject) { [self getPath:@"api/1/products" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"getProductsWithSuccess: success"); // TODO: handle response if (success) { success((AFJSONRequestOperation *)operation, responseObject); } } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"getProductsWithSuccess: failure"); if (failure) { failure((AFJSONRequestOperation *)operation, error); } }]; }; [self refreshAccessTokenWithSuccess:success failure:failure]; } 

如果需要的话,检查令牌过期并刷新它的方法是:

 - (void)refreshAccessTokenWithSuccess:(YFRailsSaasApiClientSuccess)success failure:(YFRailsSaasApiClientFailure)failure { NSLog(@"refreshAccessTokenWithSuccess"); if (self.credential == nil) { if (failure) { NSMutableDictionary *errorDetail = [NSMutableDictionary dictionary]; [errorDetail setValue:@"Failed to get credentials" forKey:NSLocalizedDescriptionKey]; NSError *error = [NSError errorWithDomain:@"world" code:200 userInfo:errorDetail]; failure(nil, error); } return; } if (!self.credential.isExpired) { NSLog(@"refreshAccessTokenWithSuccess: credential has not expired"); if (success) { success(nil, nil); } return; } NSLog(@"refreshAccessTokenWithSuccess: refreshing credential"); [self authenticateUsingOAuthWithPath:@"oauth/token" refreshToken:self.credential.refreshToken success:^(AFOAuthCredential *newCredential) { NSLog(@"Successfully refreshed OAuth credentials %@", newCredential.accessToken); self.credential = newCredential; [AFOAuthCredential storeCredential:newCredential withIdentifier:self.serviceProviderIdentifier]; if (success) { success(nil, nil); } } failure:^(NSError *error) { NSLog(@"An error occurred refreshing credential: %@", error); if (failure) { failure(nil, error); } }]; } 

完整的源代码在GitHub: https : //github.com/yellowfeather/rails-saas-ios 。