简体   繁体   中英

HMAC-SHA1 for iOS to match Yahoo's OAuth API call

I know HMAC-SHA1 functions are easily available on SO, but I have tried all of them to generate an OAuth signature but with no success.

Since the code sample given by yahoo is written in Java I am not sure If I am following the same HMAC-SHA1 algorithm.

Here is the method which I use to generate it:

- (NSString *)generateOAuthHeader
{
    NSString *apiURL = @"https://weather-ydn-yql.media.yahoo.com/forecastrss";
    NSString *oauth_consumer_key = @"dj0yJmk9V004dENIbkd6dXh3JnM9Y29uc3VtZXJzZWNyZXQmc3Y9MCZ4PTg0";
    NSString *consumerSecret = @"9b54fad8d2bccedaa17eddfe342a0178ee72eb34";
    NSString *oauth_nonce = @"840eee23-f521-4d52-bca9-3a715894f22";
    NSString *oauth_signature_method = @"HMAC-SHA1";
    NSString *oauth_timestamp = [NSString stringWithFormat:@"%.0f", [[NSDate date] timeIntervalSince1970]];
    NSString *oauth_version = @"1.0";

    NSString *encodedApiURL = urlformdata_encode(apiURL);

    NSString *parameters = NSString *parameters = [NSString stringWithFormat:@"oauth_consumer_key=%@&oauth_nonce=%@&oauth_signature_method=%@&oauth_timestamp=%@&oauth_version=%@&lat=%f&lon=%f&format=json", oauth_consumer_key, oauth_nonce, oauth_signature_method, oauth_timestamp, oauth_version, 30.707640, 76.703553, nil];
    NSString *encodedParameters = urlformdata_encode(parameters);

    NSString *signature = [NSString stringWithFormat:@"GET&%@&%@&", encodedApiURL, encodedParameters];
    signature = [self hmacsha1:signature secret:consumerSecret];

NSString *authorizationHeader = [NSString stringWithFormat:@"OAuth oauth_consumer_key=\"%@\", oauth_nonce=\"%@\", oauth_signature_method=\"%@\", oauth_timestamp=\"%@\", oauth_version=\"%@\", oauth_signature=\"%@\"", oauth_consumer_key, oauth_nonce, oauth_signature_method, oauth_timestamp, oauth_version, signature,  nil];

return authorizationHeader;
}

But I always end up having a 401 error meaning the signature is not correct.

I created a public repo in objective-c so any one can try it out, it is available here: https://github.com/userException/yahooOAuthiOS

The one minute detail which is not mentioned on Yahoo's page is you have to append "&" to the consumer secret while creating HMA-SHA1 encrypted string. Because of this the HMAC-SHA1 string was not what the yahoo's server was comparing it with.

I have committed my changes in the same repo mentioned in the question, if you need to have the Swift/Objective-C version of it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM