新浪受權認證(不用SDK)

微博開放平臺:http://open.weibo.com/web

微博開放接口的調用,如發微博、關注等,都是須要獲取用戶身份認證的。目前微博開放平臺用戶身份鑑權主要採用的是OAuth2.0。另外,爲了方便開發者開發、測試本身的應用,咱們還提供了Basic Auth的身份鑑權方式,但Basic Auth僅適用於應用所屬的開發者本身調用接口。json

1.獲取新浪的登陸頁面(UIWebView)api

2.用戶輸入獲得狀態碼(code)session

3.用code換令牌 Token測試

 

#import "ViewController.h"ui

 

#define kAppKey @""微博註冊應用以後獲得atom

#define kAppSecret @""微博註冊應用以後獲得url

#define kRedirect_url @"https://www.baidu.com"spa

 

#define kAccessTokenKey @"kAccessTokenKey"code

#define kExpiresTime @"kExpiresTime"

#define kUserID @"kUserID"

 

@interface ViewController ()<UIWebViewDelegate>

@property (strong,nonatomic) UIWebView * webView;

@end

 

@implementation ViewController

- (IBAction)Login:(UIButton *)sender {

    //1.使用oauth2/authorize發起請求

    //拼接網址

    NSString * urlString = [NSString stringWithFormat:@"https://api.weibo.com/oauth2/authorize?client_id=%@&redirect_uri=%@",kAppKey,kRedirect_url];

    NSURL * url = [NSURL URLWithString:urlString];

    //建立請求

    NSURLRequest * request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:60];

    //建立頁面

    self.webView = [[UIWebView alloc]initWithFrame:self.view.bounds];  

    _webView.delegate = self;

    [self.view addSubview:_webView];

    //加載

    [_webView loadRequest:request]; 

}

- (IBAction)Logout:(UIButton *)sender {

    NSUserDefaults * userDefault = [NSUserDefaults standardUserDefaults];

    [userDefault setObject:nil forKey:kAccessTokenKey];

    [userDefault setObject:nil forKey:kExpiresTime];

    [userDefault setObject:nil forKey:kUserID];

    [userDefault synchronize];

}

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{

    //return YES 加載 return NO 不加載

    //2.獲取code狀態碼

    NSRange range = [[request.URL relativeString]rangeOfString:@"code="];

    if (range.length != 0 ) {

        //解析code

        NSString * code = [[request.URL relativeString]substringFromIndex:range.location+range.length];//截取出來

        [self.webView removeFromSuperview];//獲取到就不須要了

        NSLog(@"%@",code);

        //3.換取令牌

        //發送Post請求

        NSURL * url =[NSURL URLWithString:@"https://api.weibo.com/oauth2/access_token"];

        NSMutableURLRequest * upRequest = [NSMutableURLRequest requestWithURL:url];//用POST而不是用GET

        [upRequest setHTTPMethod:@"POST"];

        NSURLSession * session =[NSURLSession sharedSession];

        NSString * dataString = [NSString stringWithFormat:@"client_id=%@&client_secret=%@&grant_type=authorization_code&code=%@&redirect_uri=%@&",kAppKey,kAppSecret,code,kRedirect_url];

        NSData * updata = [dataString dataUsingEncoding:NSUTF8StringEncoding];

        NSURLSessionUploadTask * upLoadTask = [session uploadTaskWithRequest:upRequest fromData:updata completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

            NSDictionary * dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];//用字典封裝json數據

            NSLog(@"%@",dataDic);

            //咱們要用的---access_token  expires_in  uid

            NSString * accesstoken = [dataDic objectForKey:@"access_token"];

            NSString * expiresin = [dataDic objectForKey:@"expires_in"];

            NSString * uid = [dataDic objectForKey:@"uid"];

            //保存下來

            NSUserDefaults * userDefault = [NSUserDefaults standardUserDefaults];

            [userDefault setObject:accesstoken forKey:kAccessTokenKey];

            [userDefault setObject:expiresin forKey:kExpiresTime];

            [userDefault setObject:uid forKey:kUserID];

            [userDefault synchronize];

        }];

        [upLoadTask resume];

        return NO;

    }else{

        return YES;

    }

}

相關文章
相關標籤/搜索