博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
新浪微博OAUTH方法-iPhone
阅读量:6541 次
发布时间:2019-06-24

本文共 8965 字,大约阅读时间需要 29 分钟。

1, 在第一步获取Request Token时,需要使用Consumer Key和API Key Secret进行签名 的Consumer Key Secret。

方法:oauth/request_token
获取request_token之后,要做一件事情,就是让用户登录,调出新浪微博登录页面:
- (NSString*)authorizeUrl{
    //
    NSString *baseUrl = [NSString stringWithFormat:@"http://%@/oauth/authorize", SINA_T_HOST];
    NSString *url = [NSString stringWithFormat:@"%@?oauth_token=%@&oauth_token_secret=%@&oauth_callback%@", baseUrl, self.oauth_token, self.oauth_token_secret, @"oob"];
    return url;
}
oauth_token 和oauth_token_secret是第一步的请求返回的。
登录完,用户授权后,会生成一个授权码,这个授权码在下一步获取access token的时候使用,就是下面的参数pin。
2, 在第二步换取Access Token时,需要使用Consumer Key,API Key Secret、Request Token和Request Token Secret进行签名。而Request Token和Request Token Secret对应签名中的Token和Token Secret 
方法:oauth/access_token
举例:
#define SINA_T_HOST                            @"api.t.sina.com.cn"//api.t.sina.com.cn
#define SINA_WEIBO_APP_KEY            @"你的Consumer Key"
#define SECRET                                      @"你的API Key Secret"
#define OAUTH_VERSION                              @"1.0"
#define OAUTH_SIGNATURE_METHOD        @"HMAC-SHA1"
获取Request Token
- (BOOL)getRequestToken{
    BOOL bRes = NO;
    self.uploadPool = [[NSAutoreleasePool alloc] init];
    self.characterBuffer = [NSMutableData data];
    done = NO;
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    
    NSString *baseUrl = [NSString stringWithFormat:@"http://%@/oauth/request_token", SINA_T_HOST];
    
    CFUUIDRef theUUID = CFUUIDCreate(NULL);
    CFStringRef string = CFUUIDCreateString(NULL, theUUID);
    CFRelease(theUUID);
    NSString *nonce = [(NSString*)string copy];
    CFRelease(string);
    
    NSString * timestamp = [NSString stringWithFormat:@"%0.0f",[[NSDate date] timeIntervalSince1970]];
    
    
    NSMutableDictionary* info = [NSMutableDictionary dictionaryWithObjectsAndKeys:SINA_WEIBO_APP_KEY,@"oauth_consumer_key",
                                 OAUTH_SIGNATURE_METHOD,@"oauth_signature_method",
                                 timestamp,@"oauth_timestamp",
                                 nonce,@"oauth_nonce",
                                 OAUTH_VERSION,@"oauth_version",nil];
    
    NSString* url = hmac_sha1_signature(@"GET", baseUrl, info, @"");
    
    NSLog(@"%@", url);
    
    
    NSString *oauthHeader = [NSString stringWithFormat:@"OAuth realm=\"%@\", oauth_consumer_key=\"%@\", oauth_signature_method=\"%@\", oauth_signature=\"%@\", oauth_timestamp=\"%@\", oauth_nonce=\"%@\", oauth_version=\"1.0\"",
                             @"",
                             [info valueForKey:@"oauth_consumer_key"],
                             [info valueForKey:@"oauth_signature_method"],
                             [info valueForKey:@"oauth_signature"],
                             [info valueForKey:@"oauth_timestamp"],
                             [info valueForKey:@"oauth_nonce"]];
   
 //NSLog(@"oauthHeader: %@", oauthHeader);
    
    
    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:baseUrl]];
    [theRequest setHTTPMethod:@"GET"];
    [theRequest setValue:oauthHeader forHTTPHeaderField:@"Authorization"];
    
    connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    [self performSelectorOnMainThread:@selector(httpConnectStart) withObject:nil waitUntilDone:NO];
    if (connection != nil) {
        do {
            [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
        } while (!done);
    }
    
    NSString *stringData = [[NSString alloc] initWithData: characterBuffer encoding: NSUTF8StringEncoding];
    NSLog(@"%@",stringData);
    
    //oauth_token=43dd8e6574fc1d1e1c5ae4ecf534b763&oauth_token_secret=015c39cad2c0bf264c8b46896f5d5f98
    NSRange range = [stringData rangeOfString:@"oauth_token"];
    NSRange rangeSecret = [stringData rangeOfString:@"oauth_token_secret"];
    
    if(range.location != NSNotFound && rangeSecret.location != NSNotFound){
        
        NSArray *sep = [stringData componentsSeparatedByString:@"&"];
        if([sep count] >= 2){
            
            NSArray *sep1 = [[sep objectAtIndex:0] componentsSeparatedByString:@"="];
            if([sep1 count] >= 2){
                self.oauth_token = [sep1 objectAtIndex:1];
                bRes = YES;
            }
            NSArray *sep2 = [[sep objectAtIndex:1] componentsSeparatedByString:@"="];
            if([sep2 count] >= 2){
                self.oauth_token_secret = [sep2 objectAtIndex:1];
                bRes = YES;
            }
            
        }
    }
    
    [stringData release];
    
    if(bRes){
        [self.tSinaInfo_ setObject:self.oauth_token forKey:@"oauth_token"];
        [self.tSinaInfo_ setObject:self.oauth_token_secret forKey:@"oauth_token_secret"];
        [self saveInformation];
    }
    
 
   // Release resources used only in this thread.
    self.connection = nil;
    [uploadPool release];
    self.uploadPool = nil;
    
    return bRes;
}
获取Access Token
- (BOOL)getAccessToken{
    BOOL bRes = NO;
    self.uploadPool = [[NSAutoreleasePool alloc] init];
    self.characterBuffer = [NSMutableData data];
    done = NO;
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    
    NSString *baseUrl = [NSString stringWithFormat:@"http://%@/oauth/access_token", SINA_T_HOST];
    
    CFUUIDRef theUUID = CFUUIDCreate(NULL);
    CFStringRef string = CFUUIDCreateString(NULL, theUUID);
    CFRelease(theUUID);
    NSString *nonce = [(NSString*)string copy];
    CFRelease(string);
    
    NSString * timestamp = [NSString stringWithFormat:@"%0.0f",[[NSDate date] timeIntervalSince1970]];
    
    
    NSMutableDictionary* info = [NSMutableDictionary dictionaryWithObjectsAndKeys:SINA_WEIBO_APP_KEY,@"oauth_consumer_key",
                                 OAUTH_SIGNATURE_METHOD,@"oauth_signature_method",
                                 timestamp,@"oauth_timestamp",
                                 nonce,@"oauth_nonce",
                                 self.oauth_token,@"oauth_token",
                                 self.pin,@"oauth_verifier",
                                 OAUTH_VERSION,@"oauth_version",nil];
    
    hmac_sha1_signature(@"GET", baseUrl, info, self.oauth_token_secret);
    
  
  //NSLog(@"%@", url);
    
    
    NSString *oauthHeader = [NSString stringWithFormat:@"OAuth realm=\"%@\", oauth_consumer_key=\"%@\", oauth_token=\"%@\", oauth_signature_method=\"%@\", oauth_signature=\"%@\", oauth_timestamp=\"%@\",oauth_verifier=\"%@\", oauth_nonce=\"%@\", oauth_version=\"1.0\"",
                             @"",
                             [info valueForKey:@"oauth_consumer_key"],
                             [info valueForKey:@"oauth_token"],
                             [info valueForKey:@"oauth_signature_method"],
                             [info valueForKey:@"oauth_signature"],
                             [info valueForKey:@"oauth_timestamp"],
                             [info valueForKey:@"oauth_verifier"], //授权码
                             [info valueForKey:@"oauth_nonce"]];
   // NSLog(@"oauthHeader: %@", oauthHeader);
    
    
    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:baseUrl]];
    [theRequest setHTTPMethod:@"GET"];
    [theRequest setValue:oauthHeader forHTTPHeaderField:@"Authorization"];
    
    connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    [self performSelectorOnMainThread:@selector(httpConnectStart) withObject:nil waitUntilDone:NO];
    if (connection != nil) {
        do {
            [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
        } while (!done);
    }
    
    NSString *stringData = [[NSString alloc] initWithData: characterBuffer encoding: NSUTF8StringEncoding];
    //NSLog(@"%@",stringData);
    
    NSRange range = [stringData rangeOfString:@"oauth_token"];
    NSRange rangeSecret = [stringData rangeOfString:@"oauth_token_secret"];
    
    if(range.location != NSNotFound && rangeSecret.location != NSNotFound){
        
        NSArray *sep = [stringData componentsSeparatedByString:@"&"];
        if([sep count] >= 2){
            
            NSArray *sep1 = [[sep objectAtIndex:0] componentsSeparatedByString:@"="];
            if([sep1 count] >= 2){
                self.access_token = [sep1 objectAtIndex:1];
                bRes = YES;
            }
            NSArray *sep2 = [[sep objectAtIndex:1] componentsSeparatedByString:@"="];
            if([sep2 count] >= 2){
                self.access_token_secret = [sep2 objectAtIndex:1];
                bRes = YES;
            }
            
        }
    }
    
    if(bRes){
        [self.tSinaInfo_ setObject:self.access_token forKey:@"access_token"];
        [self.tSinaInfo_ setObject:self.access_token_secret forKey:@"access_token_secret"];
        [self saveInformation];
    }
    
    [stringData release];
    
    
    // Release resources used only in this thread.
    self.connection = nil;
    [uploadPool release];
    self.uploadPool = nil;
    
    return bRes;
}
签名函数: hmac_sha1_signature
 NSString* hmac_sha1_signature(NSString* method, NSString* baseUrl, NSDictionary*param, NSString* token_secret) {
    
    NSArray *sortedkeys = [[param allKeys] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
    NSMutableString *mutUrlParam = [NSMutableString stringWithString:@""];
    
    unsigned i, c = [sortedkeys count];
    for (i=0; i<c; i++) {
        NSString *k=[sortedkeys objectAtIndex:i];
        NSString *v=[param objectForKey:k];
        if(i>0){
            [mutUrlParam appendString:@"&"];
        }
        [mutUrlParam appendString:k];
        [mutUrlParam appendString:@"="];
        [mutUrlParam appendString:[URICode escapeURIComponent:v]];// URI 编码
    }
    
    NSString *urlEncodeBaseUrl = [URICode escapeURIComponent:baseUrl]; // URI 编码
    NSString *urlParam = (NSString*)mutUrlParam;
    urlParam = [URICode escapeURIComponent:urlParam]; // URI 编码
    
    
//1.generate Signature BaseString
    NSString *sbs = [NSString stringWithFormat:@"%@&%@&%@", method, urlEncodeBaseUrl, urlParam];
    
    //NSLog(@"%@", sbs);
    
    NSString *key = [NSString stringWithFormat:@"%@&%@",SECRET, token_secret];
    
    NSString *oauth_signature = [SHA1 hmac_sha1:key text:sbs];
    
    [param setValue:oauth_signature forKey:@"oauth_signature"];
    
  
  //oauth_signature = [URICode escapeURIComponent:oauth_signature];
    
    //NSLog(@"oauth_signature = %@", oauth_signature);
    
    NSMutableString *urlParams = [NSMutableString stringWithString:@""];
    NSArray *keys=[param allKeys];
    i, c=[keys count];
    for (i=0; i<c; i++) {
        NSString *k=[keys objectAtIndex:i];
        NSString *v=[param objectForKey:k];
        
        NSString *paramStr = [NSString stringWithFormat:@"&%@=%@",k,[URICode escapeURIComponent:v]];
        [urlParams appendString:paramStr];
    }
    
    [urlParams replaceCharactersInRange:NSMakeRange(0,1) withString:@""];
    
    return (NSString*)urlParams;
}

转载地址:http://pusdo.baihongyu.com/

你可能感兴趣的文章
memcache--mysql测试
查看>>
拷贝构造函数、拷贝函数、析构函数
查看>>
实战CGLib系列之proxy篇(一):方法拦截MethodInterceptor
查看>>
php 字符串截取
查看>>
ttcn-3
查看>>
00.java虚拟机的基本结构概念
查看>>
深入浅出 ES6:ES6 与 Babel - Broccoli 的联用
查看>>
ThreadLocal使用出现的问题
查看>>
关于十六进制和八进制负数的问题
查看>>
连接池并发的实现原理
查看>>
创建Pch预编译文件
查看>>
阿里云Centos配置iptables防火墙
查看>>
UML类图几种关系的总结
查看>>
PHP面试题汇总
查看>>
LeetCode (11): Container With Most Water
查看>>
【技巧】easyUI的datagrid,如何在翻页以后仍能记录被选中的行
查看>>
在CentOS7中配置网络时常见的LSB加载失败问题
查看>>
经过强制类型转换以后,变量a, b的值分别为( )short a = 128; byte b = (byte) a;
查看>>
ubuntu下msmtp+mutt的安装和配置
查看>>
蓝桥杯-学校的第一次练习题
查看>>