#iOS开发笔记#OAuth 2.0在iOS客户端的实现

来源:互联网 发布:php7编译 nginx 编辑:程序博客网 时间:2024/05/16 06:09

一、OAuth 2.0介绍

详细参见wikipedia和百度百科,http://oauth.net/2/

二、所用工具和环境

IDE:XCode 6
Language:Objective-C
Library:https://github.com/nxtbgthng/OAuth2Client

三、实现步骤

具体步骤参考https://github.com/nxtbgthng/OAuth2Client,以下为个人补充

1.下载library包并解压
2.Manually including the library in your Xcode project(iOS projects)

3.Configure your Client

在AppDelegate中重写+(void)initialize;

<span style="font-size:14px;">+(void)initialize{    //The following line is to protect this class from being run multi times    if (self == [AppDelegate self]) {                //Configue OAuth2Client        [[NXOAuth2AccountStore sharedStore] setClientID:CLIENT_ID                                                 secret:SECRET                                       authorizationURL:[NSURL URLWithString:AUTH_URL]                                               tokenURL:[NSURL URLWithString:TOKEN_URL]                                            redirectURL:[NSURL URLWithString:REDIRECT_URL]                                         forAccountType:FOR_ACCOUNT_TYPE];    }}</span>

4.Requesting Access to a Service

此处选用第一种(Username and Password),添加之后的两个异步的方法(OnSuccess,OnFailure)。

成功的话,会在OnSuccess方法中得到NSNotification *aNotification,进而可以得到account和token

<span style="font-size:14px;">NXOAuth2Account *account =[aNotification.userInfo objectForKey:@"NXOAuth2AccountStoreNewAccountUserInfoKey"];    //NSLog(@"account token: %@", account.accessToken);    NXOAuth2AccessToken *authToken =account.accessToken;        NSLog(@"accessToken:%@", authToken.accessToken);        //NSString    NSLog(@"refreshToken:%@", authToken.refreshToken);      //NSString    NSLog(@"tokenType:%@", authToken.tokenType);            //NSString        NSDate *expireDate = authToken.expiresAt;    NSLog(@"expiresDate:%@", expireDate);                   //NSDate</span>

5.Invoking a Request

使用上一步得到的account请求服务端的内容

<span style="font-size:14px;">//Invoke a request for a service using authentication- (void)invokeRequest:(NXOAuth2Account *)account{    NSLog(@"invokeRequest");    [NXOAuth2Request performMethod:@"GET"                        onResource:[NSURL URLWithString:ON_RESOURCE_URL]                   usingParameters:nil                       withAccount:account               sendProgressHandler:^(unsigned long long bytesSend, unsigned long long bytesTotal) {                   // e.g., update a progress indicator                   NSLog(@"requestProcess:%llu", bytesSend/bytesTotal);               }               responseHandler:^(NSURLResponse *response, NSData *responseData, NSError *error){                   // Process the response                   NSLog(@"URLResponse:%@", response);                   NSLog(@"responseData:%@", responseData);                   [self parseResponse:responseData];               }];}</span>

6.Parse Response Data

将上一步中得到的responseData转换成NSDictionary(iOS 4.0 以上)

<span style="font-size:14px;">- (void)parseResponse:(NSData *)data{    NSError *error = nil;    id object = [NSJSONSerialization                 JSONObjectWithData:data                 options:0                 error:&error];        if(error) {        /* JSON was malformed, act appropriately here */        NSLog(@"JSON was malformed, act appropriately here");    }        // the originating poster wants to deal with dictionaries;    // assuming you do too then something like this is the first    // validation step:    if([object isKindOfClass:[NSDictionary class]])    {        NSDictionary *result = object;        NSLog(@"result is a dictionary: %@", result);        /* proceed with results as you like; the assignment to         an explicit NSDictionary * is artificial step to get         compile-time checking from here on down (and better autocompletion         when editing). You could have just made object an NSDictionary *         in the first place but stylistically you might prefer to keep         the question of type open until it's confirmed */    }    else    {        NSLog(@"result is not a dictionary");        /* there's no guarantee that the outermost object in a JSON         packet will be a dictionary; if we get here then it wasn't,         so 'object' shouldn't be treated as an NSDictionary; probably         you need to report a suitable error condition */    }}</span>

0 0
原创粉丝点击