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/ 
本文版權歸煙臺傑瑞教育科技有限公司和博客園共有,歡迎轉載,但未經做者贊成必須保留此段聲明,且在文章頁面明顯位置給出原文鏈接,不然保留追究法律責任的權利。
相關文章
相關標籤/搜索