IOS开发之新浪微博OAuth2

  说明:微博开放接口的调用,如发微博、关注等,都是须要获取用户身份认证的。目前微博开放平台用户身份鉴权主要采用的是OAuth2.0。为了方便开发者开发、测试本身的应用。web

  OAuth2.0较1.0相比,整个受权验证流程更简单更安全,也是将来最主要的用户身份验证和受权方式。api

步骤一:建立应用

 下面我以本公司测试帐号为例,建立应用步骤能够参考新浪的官方API 地址:http://open.weibo.com应用建立好停留在开发阶段便可使用,本例的应用信息以下图安全

 

步骤二:获取token号码

 

  经过webView加载连接其中client_id为应用的app Key, redirect_uri的值为公司跳转连接这里我以本公司连接为例子app

UIWebView  * web=[[UIWebView alloc] init]; web.frame=self.view.bounds;
NSString*str=@"https://api.weibo.com/oauth2/authorize?client_id=3272733387&redirect_uri=http://www.21-sun.com";

    NSURL * url=[NSURL URLWithString:str];
    NSURLRequest *request=[NSURLRequest requestWithURL:url];
    [web loadRequest:request];
    [self.view addSubview:web];
web.delegate=self;

  效果界面以下,登陆完成受权:测试

 

  在返回的连接中后面会拼有参数code,此code咱们须要备用,如图所示,咱们能够经过webView的代理来截取返回连接url

 

#pragma mark - 容许代理加载请求
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
NSString * str=request.URL.absoluteString;
if([str containsString:@"http://www.21-sun.com/?code="]){
     NSInteger index=[str rangeOfString:@"="].location;
        NSString * code=[str substringFromIndex:index+1];
        return NO;
 }
return YES;
}

  请求access_token,如图所示,采用下面连接请求spa

//client_id true     string  申请应用时分配的AppKey。3d

//client_secret    true     string  申请应用时分配的AppSecret。代理

//grant_type  true     string  请求的类型,填写authorization_codecode

//code true     string   上面得到的code值。

//redirect_uri true     string  回调地址,需需与注册应用里的回调地址一致。

 

  代码以下

- (void)_getToken:(NSString *) code{

    NSDictionary *dic=@{@"client_id":@"3272733387",@"client_secret":@"10003f9922c9d0e0fefb03500c8d4dbc",@"grant_type":@"authorization_code",@"code":data,@"redirect_uri":@"http://www.21-sun.com"};

   

   AFHTTPRequestOperationManager * manager=[AFHTTPRequestOperationManager manager];  manager.responseSerializer.acceptableContentTypes=[NSSet setWithObject:@"text/plain"];

[manager  POST:@"https://api.weibo.com/oauth2/access_token" parameters:dic success:^(AFHTTPRequestOperation *operation, NSDictionary * responseObject) {

       NSString * token=responseObject[@"access_token"];    

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

NSLog(@"请求失败");

}];

}

此时用咱们获取的access_token码就能够作不少事情了。

 

做者: 杰瑞教育
出处: http://www.cnblogs.com/jerehedu/ 
本文版权归烟台杰瑞教育科技有限公司和博客园共有,欢迎转载,但未经做者赞成必须保留此段声明,且在文章页面明显位置给出原文链接,不然保留追究法律责任的权利。
相关文章
相关标签/搜索