如何在ios(Objective c)中生成Oauth签名?

时间:2018-10-28 10:51:37

标签: ios objective-c

最近5到6天内,我一直陷入这个问题,我想从twitter user_timeline api获取用户时间轴供稿。我收到错误代码32,其中消息无法验证您的身份。我尝试了很多但没有成功。请帮助我摆脱这个问题。任何帮助,将不胜感激。预先感谢。

-(void)getNewTimelineoFUser: (NSString *)userId{
NSString *oauth_timestamp = [NSString stringWithFormat:@"%lu", (unsigned long)[NSDate.date timeIntervalSince1970]];
NSString *oauth_nonce =  [self genRandString];
NSString *oauth_consumer_key = @"**************";
NSString *oauth_token = @"*****************************************";
NSString *oauth_signature_method = @"HMAC-SHA1";
NSString *oauth_version = @"1.0";
NSMutableDictionary *standardParameters = [NSMutableDictionary dictionary];
[standardParameters setValue:@"true" forKey:@"include_entities"];
[standardParameters setValue:oauth_consumer_key     forKey:@"oauth_consumer_key"];
[standardParameters setValue:oauth_nonce            forKey:@"oauth_nonce"];
[standardParameters setValue:oauth_signature_method forKey:@"oauth_signature_method"];
[standardParameters setValue:oauth_timestamp        forKey:@"oauth_timestamp"];
[standardParameters setValue:oauth_version          forKey:@"oauth_version"];
[standardParameters setValue:oauth_token    forKey:@"oauth_token"];

NSString *parametersString = @"";

parametersString = [parametersString stringByAppendingString:[NSString stringWithFormat:@"%@=%@&",[self encodingString:@"include_entities"],[self encodingString:@"true"]]];
parametersString = [parametersString stringByAppendingString:[NSString stringWithFormat:@"%@=%@&",[self encodingString:@"oauth_consumer_key"],[self encodingString:oauth_consumer_key]]];
parametersString = [parametersString stringByAppendingString:[NSString stringWithFormat:@"%@=%@&",[self encodingString:@"oauth_nonce"],[self encodingString:oauth_nonce]]];
parametersString = [parametersString stringByAppendingString:[NSString stringWithFormat:@"%@=%@&",[self encodingString:@"oauth_signature_method"],[self encodingString:oauth_signature_method]]];
parametersString = [parametersString stringByAppendingString:[NSString stringWithFormat:@"%@=%@&",[self encodingString:@"oauth_timestamp"],[self encodingString:oauth_timestamp]]];
parametersString = [parametersString stringByAppendingString:[NSString stringWithFormat:@"%@=%@&",[self encodingString:@"oauth_token"],[self encodingString:oauth_token]]];
parametersString = [parametersString stringByAppendingString:[NSString stringWithFormat:@"%@=%@",[self encodingString:@"oauth_version"],[self encodingString:oauth_version]]];

NSLog(@"parameterString %@",parametersString);

/* OAUTH SIGNATURE */
NSString *request_url =   [NSString stringWithFormat:@"https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=TomCruise"] ;//@"https://api.twitter.com/1.1/statuses/user_timeline.json";
NSString *oauth_consumer_secret = @"******************";
NSString *oauth_token_secret = @"****************************************";
NSString *baseString = [@"GET" stringByAppendingFormat:@"&%@&%@", [self encodingString:request_url], [self encodingString:parametersString] ];
// append oauth token secret to consumer secret

NSLog(@"baseString %@",baseString);
NSString *secretString = [[self encodingString:oauth_consumer_secret] stringByAppendingFormat:@"&%@",[self encodingString:oauth_token_secret]];

NSLog(@"signingKey %@", secretString);

NSString *oauth_signature =  [self hmacsha1:baseString secret:secretString];
standardParameters[@"oauth_signature"] = [self encodingString:oauth_signature];

NSLog(@“宣誓签名新%@”,oauth_signature);

/* CREATE HEADER */
NSMutableArray *parameterPairs = [NSMutableArray array];
for (NSString *name in standardParameters)
{
    if(![name isEqualToString:@"include_entities"]){
        NSString *aPair = [[self encodingString:name] stringByAppendingFormat:@"=\"%@\"", [self encodingString:standardParameters[name]] ];
        [parameterPairs addObject:aPair];
    }
}

NSString *oAuthHeader = [@"OAuth " stringByAppendingFormat:@"%@", [parameterPairs componentsJoinedByString:@", "]];

NSLog(@"oauth Header %@",oAuthHeader);

NSMutableDictionary *dicParam = [[NSMutableDictionary alloc]init];

[dicParam setValue:userId forKey:@"userid"];
[dicParam setValue:@(5) forKey:@"count"];
[dicParam setValue:@"TomCruise" forKey:@"screen_name"];



NSLog(@"request url %@", request_url);
[self WebServiceAPIForString:request_url andparameter:dicParam andMethod:@"GET" authorizationToken:oAuthHeader];

}

- (NSString *)hmacsha1:(NSString *)data secret:(NSString *)key {

const char *cKey  = [key cStringUsingEncoding:NSASCIIStringEncoding];
const char *cData = [data cStringUsingEncoding:NSASCIIStringEncoding];

unsigned char cHMAC[CC_SHA1_DIGEST_LENGTH];

CCHmac(kCCHmacAlgSHA1, cKey, strlen(cKey), cData, strlen(cData), cHMAC);

NSData *HMAC = [[NSData alloc] initWithBytes:cHMAC length:sizeof(cHMAC)];

NSString *hash =  [HMAC base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];

return hash;

}

- (NSString *)encodingString:(NSString *)str

{

//return  str.utf8AndURLEncode;
NSMutableString * output = [NSMutableString string];
const unsigned char * source = (const unsigned char *)[str UTF8String];
int sourceLen = strlen((const char *)source);
for (int i = 0; i < sourceLen; ++i) {
    const unsigned char thisChar = source[i];
    if (thisChar == ' '){
        [output appendString:@"+"];
    } else if (thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' ||
               (thisChar >= 'a' && thisChar <= 'z') ||
               (thisChar >= 'A' && thisChar <= 'Z') ||
               (thisChar >= '0' && thisChar <= '9')) {
        [output appendFormat:@"%c", thisChar];
    } else {
        [output appendFormat:@"%%%02X", thisChar];
    }
}
return output;

}

-(NSString *) genRandString {
//fixing length of 4 chars
NSMutableString *randomString = [NSMutableString stringWithCapacity: 4];
NSString *letters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
for (int i=0; i<4; i++) {
    [randomString appendFormat: @"%C", [letters characterAtIndex: arc4random() % [letters length]]];
}

return randomString;

}

-(NSDictionary *)WebServiceAPIForString:(NSString *)urlforwebService andparameter:(NSMutableDictionary*)parameter andMethod:(NSString*)aMethod authorizationToken:(NSString*)authToken{

NSDictionary *allDataDictionary;
NSDictionary *headers = @{ @"Content-Type": @"application/x-www-form-urlencoded",
                           @"Authorization": authToken
                           };

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=TomCruise"]
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:10.0];

[request setHTTPMethod:@"GET"];
[request setAllHTTPHeaderFields:headers];
NSError *error=nil;
NSHTTPURLResponse *response=nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString* aStr = [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding] ;

if ([response statusCode] >= 200 && [response statusCode] < 300)
{
    allDataDictionary=[NSJSONSerialization JSONObjectWithData:urlData options:0 error:nil];
}

else{
    // allDataDictionary=[NSJSONSerialization JSONObjectWithData:urlData options:0 error:nil];
    allDataDictionary=[NSJSONSerialization JSONObjectWithData:urlData options:0 error:nil];

}

return allDataDictionary;

}

错误消息:

response {
errors =     (
            {
        code = 32;
        message = "Could not authenticate you.";
    }
);

}

2 个答案:

答案 0 :(得分:0)

  1. 您需要显示您尝试过的内容以及哪些代码不起作用。您不能在此站点中请求代码。

  2. 对于OAuth,您只需要安装TwitterKit框架(也有Cocoapod,或者您可以手动安装),然后按照此处的说明进行操作:https://github.com/twitter/twitter-kit-ios/wiki/Log-In-With-Twitter

祝你好运。

答案 1 :(得分:0)

如果您想获得Twitter的公共推文,以便可以使用TWTRAPIClient来使用TwitterKit,我不知道为什么要使用本机Oauth?

下面的代码将帮助您更多地在viewDidLoad中使用此代码:)

TWTRLogInButton *logInButton = [TWTRLogInButton buttonWithLogInCompletion:^(TWTRSession *session, NSError *error) {
        if (session) {
            if (!error && session) {

                NSLog(@"signed in with %@", [session userName]);

                TWTRAPIClient *APIClient = TWTRAPIClient.clientWithCurrentUser;
                TWTRUserTimelineDataSource *newArray =  [[TWTRUserTimelineDataSource alloc] initWithScreenName:@"TomCruise" APIClient:APIClient];
                [newArray loadPreviousTweetsBeforePosition:@"0" completion:^(NSArray<TWTRTweet *> * _Nullable tweets, TWTRTimelineCursor * _Nullable cursor, NSError * _Nullable error) {
                    for (int count=0; count<tweets.count; count++) {
                        NSLog(@"tweet text is == \n%@",[tweets[count] text]); //You can use TWTRWEET Properties here
                    }
                }];

            }
            else if (error) {

                NSString *userID = [[[[Twitter sharedInstance] sessionStore] session] userID];
                if(userID){
                    [[[Twitter sharedInstance] sessionStore] logOutUserID:userID];
                }
            }
            else {

                NSString *userID = [[[[Twitter sharedInstance] sessionStore] session] userID];

                if(userID){
                    [[[Twitter sharedInstance] sessionStore] logOutUserID:userID];
                }
            }
        } else {
            NSLog(@" dfdfhfgh error: %@", [error localizedDescription]);
        }
    }];
    logInButton.center = self.view.center;

    [logInButton layoutIfNeeded];
    [self.view addSubview:logInButton];