說明:微博開放接口的調用,如發微博、關注等,都是須要獲取用戶身份認證的。目前微博開放平臺用戶身份鑑權主要採用的是OAuth2.0。爲了方便開發者開發、測試本身的應用。web
OAuth2.0較1.0相比,整個受權驗證流程更簡單更安全,也是將來最主要的用戶身份驗證和受權方式。api
下面我以本公司測試帳號爲例,建立應用步驟能夠參考新浪的官方API 地址:http://open.weibo.com應用建立好停留在開發階段便可使用,本例的應用信息以下圖安全
經過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碼就能夠作不少事情了。