標籤:
說明:微博開放介面的調用,如發微博、關注等,都是需要擷取使用者身份認證的。目前微博開放平台使用者身份鑒權主要採用的是OAuth2.0。為了方便開發人員開發、測試自己的應用。
OAuth2.0較1.0相比,整個授權驗證流程更簡單更安全,也是未來最主要的使用者身分識別驗證和授權方式。
步驟一:建立應用
下面我以本公司測試帳號為例,建立應用步驟可以參考新浪的官方API 地址:http://open.weibo.com應用建立好停留在開發階段即可使用,本例的應用資訊如
步驟二:擷取token號碼
通過webView載入連結其中client_id為應用的app Key, redirect_uri的值為公司跳轉連結這裡我以本公司連結為例子
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的代理來截取返回連結
#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,,採用下面連結請求
//client_id true string 申請應用時分配的AppKey。
//client_secret true string 申請應用時分配的AppSecret。
//grant_type true string 請求的類型,填寫authorization_code
//code true string 上面獲得的code值。
//redirect_uri true string 回調地址,需需與註冊應用裡的回調地址一致。
代碼如下
- (void)_getToken:(NSString *) code{ NSDictionary *[email protected]{@"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/
本文著作權歸煙台傑瑞教育科技有限公司和部落格園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文串連,否則保留追究法律責任的權利。
IOS開發之新浪微博OAuth2