一、简要概述
OAuth2.0是OAuth协议的下一版本,时常用于移动客户端的开发,是一种比较安全的机制。在OAuth 2.0中,server将发行一个短有效期的access token和长生命期的refresh token。这将允许客户端无需用户再次操作而获取一个新的access token,并且也限制了access token的有效期。即当sever发送的access token过期之后,客户端会调用方法,将access token和refresh token发送给服务端,服务端将会返回新的access token和refresh token。
二、应用场景
用户登录后,服务端会发行一个有效时间的access token,同时也会发行一个长生命期的refresh token。用户在进行其他网络请求时,会把access token加入请求体中(并不需要加入refresh token)。如果在请求过程中,access token过期,返回相应的状态码。这时就回调用一个回调方法,在回调方法体中将原来的access token和refresh token发送给服务端,获取新的access token和refresh token。然后把新的access token加入刚才的请求体中,重新加载网络请求。
限定access token的有效时间,只是为了提高安全性。access token过期后重新获取并重新加载请求这一操作,用户是察觉不到的。这种机制在微信、QQ、微博等客户端中尤为常见。
三、实例代码
(1)此类继承了AFNetworking中的AFHTTPSessionManager类,并重写了里面的方法。
NetWorkCallBack.h:
#import <Foundation/Foundation.h>
#import <AFNetworking.h>
@interface NetWorkCallBack : AFHTTPSessionManager @end
NetWorkCallBack.m:
#import "NetWorkCallBack.h"
#import <SSKeychain.h>
@implementation NetWorkCallBack - (NSURLSessionDataTask *)dataTaskWithRequest:(NSMutableURLRequest *)urlRequest completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))originalCompletionHandler{ //create a completion block that wraps the original
void (^authFailBlock)(NSURLResponse *response, id responseObject, NSError *error) = ^(NSURLResponse *response, id responseObject, NSError *error)
{
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
if([httpResponse statusCode] == ){ //如果access token过期,返回错误,调用此block
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, ), ^{ //调用refreshAccesstoken方法,刷新access token。
[self refreshAccessToken:^(AFHTTPRequestOperation *operation) {
//存取新的access token,此处我使用了KeyChain存取
NSDictionary *headerInfo = operation.response.allHeaderFields;
NSString *newAccessToken = [headerInfo objectForKey:@"access-token"];
NSString *newRefreshToken = [headerInfo objectForKey:@"refresh-token"];
[SSKeychain deletePasswordForService:@"<key>" account:@"access-token"];
[SSKeychain deletePasswordForService:@"<key>" account:@"refresh-token"];
[SSKeychain setPassword:newAccessToken forService:@"<key>" account:@"access-token"];
[SSKeychain setPassword:newRefreshToken forService:@"<key>" account:@"refresh-token"]; //将新的access token加入到原来的请求体中,重新发送请求。
[urlRequest setValue:newAccessToken forHTTPHeaderField:@"access-token"]; NSURLSessionDataTask *originalTask = [super dataTaskWithRequest:urlRequest completionHandler:originalCompletionHandler];
[originalTask resume];
}];
});
}else{
NSLog(@"no auth error");
originalCompletionHandler(response, responseObject, error);
}
}; NSURLSessionDataTask *stask = [super dataTaskWithRequest:urlRequest completionHandler:authFailBlock]; return stask; }; /*
*获取新的token的方法。如何获取可以自定义,我这里用了AFNetWorking的AFHTTPRequestOperation类
*/
-(void)refreshAccessToken:(void(^)(AFHTTPRequestOperation *responseObject))refresh{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:@"<yourURL>"]; [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; //将原来的access token和refresh token发送给服务器,以获取新的token
NSString *accessToken = [SSKeychain passwordForService:@"<key>" account:@"access-token"];
NSString *refreshToken = [SSKeychain passwordForService:@"<key>" account:@"refresh-token"]; [request setValue:accessToken forHTTPHeaderField:@"access-token"];
[request setValue:refreshToken forHTTPHeaderField:@"refresh-token"]; //执行网络方法
AFHTTPRequestOperation *httpRequestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[httpRequestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation * operation, id responseObject) {
refresh(operation);
} failure:^(AFHTTPRequestOperation * operation, NSError * error) {
refresh(operation);
}];
[httpRequestOperation start];
}
@end