說明:微博開放接口的調用,如發微博、關注等,都是需要獲取用戶身份認證的。目前微博開放平臺用戶身份鑒權主要采用的是OAuth2.0。為了方便開發者開發、測試自己的應用。
OAuth2.0較1.0相比,整個授權驗證流程更簡單更安全,也是未來最主要的用戶身份驗證和授權方式。
下面我以本公司測試賬號為例,創建應用步驟可以參考新浪的官方API 地址:http://open.weibo.com應用創建好停留在開發階段即可使用,本例的應用信息如下圖
通過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 *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碼就可以做很多事情了。
新聞熱點
疑難解答