新浪微博OAUTH方法

来源:互联网 发布:遭遇网络诈骗 编辑:程序博客网 时间:2024/04/30 15:39
 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;
}
原创粉丝点击