OAuth认证 / 与新特性页面的配合使用

来源:互联网 发布:淘宝客户关系维护流程 编辑:程序博客网 时间:2024/05/21 14:57
1.什么是OAuth?
oAuth是一种协议,为用户资源的授权提供了一个安全的、开放而又简易的标准
任何第三方都可以使用oAuth认证服务,第三方若想访问用户资源即必须遵守服务提供商提供的oAuth协议

2.优点?
oAuth优点:不会使第三方触及到用户的账号密码就可以申请获得改用的资源的授权,因此是安全的 

3.OAuth认证流程是什么?
(1)获取未授权的请求标记(request token)
(2)获取用户授权的请求标记(request token)
(3)用授权的请求标记换取访问标记(access token)

4.以新浪博客为例


5.下面用代码来描述这3个步骤:
(1)我是创建了一个视图控制器类OAuthViewController,利用AFN请求数据
#import "OAuthViewController.h"#import "AFNetworking.h"#import "OAuthModel.h"#import "TabBarOrNewFeature.h"@interface OAuthViewController()<UIWebViewDelegate>@property (nonatomic, weak) UIWebView *webView;@end@implementation OAuthViewController- (void)viewDidLoad{    [super viewDidLoad];        //1.添加webView    UIWebView *webView = [[UIWebView alloc] initWithFrame:[UIScreen mainScreen].bounds];    [self.view addSubview:webView];    webView.delegate = self;    self.webView = webView;        //2.加载授权页面(带APPKey和回调url参数)    [self loadOAuthPage];}//一.加载授权页面(带APPKey和回调url参数,获得一个未授权的token标记)- (void)loadOAuthPage{    NSString *url = @"https://api.weibo.com/oauth2/authorize?client_id=2285723245&redirect_uri=https://www.baidu.com";    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];    [self.webView loadRequest:request];}#pragma mark - webView将要请求数据的时候调用,在这里截取code//二.在webView将要加载请求的时候,取得授权的token标记- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{    //    1.取得URL路径   NSString *url = request.URL.absoluteString;    //    2.将code=往后的全部截取出来    //(1)取得code=的位置    NSRange rang = [url rangeOfString:@"code="];    //(2)如果能找到    if (rang.length) {        //rang的起点+长度确定code=的位置        NSInteger loc = rang.location + rang.length;        //截取code=以后的字符串       NSString *code = [url substringFromIndex:loc];        //   3.发送请求,用code换得accessToken        [self accessTokenWithCode:code];    }            return YES;}//三.用授权的code换取accessToken访问标记- (void)accessTokenWithCode:(NSString *)code{    //AFN请求数据步骤:    //1.创建管理者    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];            NSMutableDictionary *dict = [NSMutableDictionary dictionary];    dict[@"client_id"] = @"2285723245";    dict[@"client_secret"] = @"089ade96a1569faf2f7c686fdf5a6291";    dict[@"grant_type"] = @"authorization_code";    dict[@"code"] = code;    dict[@"redirect_uri"] = @"https://www.baidu.com";    //2.发送请求    [manager POST:@"https://api.weibo.com/oauth2/access_token" parameters:dict success:^(NSURLSessionDataTask *task, id responseObject) {        //(1)将取得的数据赋值给模型        OAuthModel *mode = [OAuthModel modelWithDict:responseObject];                //(2)利用归档存取模型数据        NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];        NSString *filePath= [path stringByAppendingPathComponent:@"account.data"];        [NSKeyedArchiver archiveRootObject:mode toFile:filePath];                //(3)请求数据成功了,选择根控制器        [TabBarOrNewFeature tabBarOrNewFeature];            } failure:^(NSURLSessionDataTask *task, NSError *error) {            }];}

(2)OAuthModel模型类,数据请求成功后将数据赋值给模型,然后将模型用归档存到本地
#import <Foundation/Foundation.h>@interface OAuthModel : NSObject <NSCoding>@property (nonatomic,copy) NSString *access_token;@property (nonatomic ,assign) long long expires_in;@property (nonatomic ,assign) long long remind_in;@property (nonatomic ,assign) long long uid;- (id)initWithDict:(NSDictionary *)dict;+ (id)modelWithDict:(NSDictionary *)dict;@end#import "OAuthModel.h"@implementation OAuthModel- (id)initWithDict:(NSDictionary *)dict{    if (self = [super init]) {        [self setValuesForKeysWithDictionary:dict];    }    return self;}+ (id)modelWithDict:(NSDictionary *)dict{    return [[self alloc] initWithDict:dict];}//读取的时候调用- (id)initWithCoder:(NSCoder *)aDecoder{    if (self=[super init])    {        self.access_token = [aDecoder decodeObjectForKey:@"access_token"];        self.remind_in = [aDecoder decodeInt64ForKey:@"remind_in"];        self.expires_in = [aDecoder decodeInt64ForKey:@"expires_in"];        self.uid = [aDecoder decodeInt64ForKey:@"uid"];            }    return self;}//存入的时候调用- (void)encodeWithCoder:(NSCoder *)aCoder{    [aCoder encodeObject:self.access_token forKey:@"name"];    [aCoder encodeInt64:self.remind_in forKey:@"remind_in"];    [aCoder encodeInt64:self.expires_in forKey:@"expires_in"];    [aCoder encodeInt64:self.uid forKey:@"uid"];}@end

(3)新特性页面我已经写过,这里就不说了,具体可以看下我的分类文章。
(4)在AppDelegate里面先取出利用归档存到本地的模型数据,然后对根视图进行切换
//读取存储的账号    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];    NSString *filePath= [path stringByAppendingPathComponent:@"account.data"];    OAuthModel *model = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];        //有账号,说明登陆过    if (model) {        [TabBarOrNewFeature tabBarOrNewFeature];//判断有没有新版本,再选择根控制器    }else{//没有登录过,弹出认证输入账号密码        self.window.rootViewController = [[OAuthViewController alloc] init];    }

(5)关于新特性页面和标签栏页面的切换,我已经封装成了工具类
+ (void)tabBarOrNewFeature{    NSString *key = @"CFBundleVersion";    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];        //存入本地版本    NSString *lastVersion =  [defaults stringForKey:key];    //取得当前版本    NSString *currentVersion = [NSBundle mainBundle].infoDictionary[key];        //如果之前的版本和当前的版本相同 说明没有新版本    if ([currentVersion isEqualToString:lastVersion]) {        [UIApplication sharedApplication].keyWindow.rootViewController = [[MainTabBarViewController alloc] init];    }else{//说明有新版本,显示新特性页面        [UIApplication sharedApplication].keyWindow.rootViewController = [[NewFeature alloc] init];                //将新版本存入本地        [defaults setObject:currentVersion forKey:key];        [defaults synchronize];    }}



0 0
原创粉丝点击