iOS OAuth签名生成?
我一直在寻找为Oauth标题生成签名的代码,而男孩却很痛苦。 我的目标平台是iOS,我需要为TradeKing API执行此操作。 基本上他们的查询需要OAuth(不需要使用Oauth工作流提前授权我的应用程序供个人使用;我只需要使用TradeKing提供给我的密钥使用oauth标头对每个查询进行签名)。 这是一些示例文档: GetPost
我找到的最好的示例代码如下: https : //github.com/Christian-Hansen/simple-oauth1
我能够按照他的例子来显示LinkedIn库登录。 然后,我调整了TradeKing REST查询的代码,但由于签名无效,它失败了。 这让我很担心,因为生成签名的代码是最复杂的部分……而且我不确定我是否正确使用了他的代码。 在下面的代码中,我将oauth键和秘密更改为Xs。
/* THE URL REQUEST */ NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://api.tradeking.com/v1/market/ext/quotes.xml?symbols=aapl"]]; request.HTTPMethod = @"GET"; /* OAUTH FIELDS */ NSString *oauth_timestamp = [NSString stringWithFormat:@"%lu", (unsigned long)[NSDate.date timeIntervalSince1970]]; NSString *oauth_nonce = [NSString getNonce]; NSString *oauth_consumer_key = @"xxxxxxx"; NSString *oauth_token = @"xxxxxxx"; NSString *oauth_signature_method = @"HMAC-SHA1"; NSString *oauth_version = @"1.0"; NSMutableDictionary *standardParameters = [NSMutableDictionary dictionary]; [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 = CHQueryStringFromParametersWithEncoding(standardParameters, NSUTF8StringEncoding); /* OAUTH SIGNATURE */ NSString *request_url = @"https://api.tradeking.com/v1/market/ext/quotes.xml?symbols=aapl"; NSString *oauth_consumer_secret = @"xxxxxx"; NSString *oauth_token_secret = @"xxxx"; NSString *baseString = [@"GET" stringByAppendingFormat:@"&%@&%@", request_url.utf8AndURLEncode, parametersString.utf8AndURLEncode]; // append oauth token secret to consumer secret NSString *secretString = [oauth_consumer_secret.utf8AndURLEncode stringByAppendingFormat:@"&%@", oauth_token_secret.utf8AndURLEncode]; NSString *oauth_signature = [self.class signClearText:baseString withSecret:secretString]; standardParameters[@"oauth_signature"] = oauth_signature; /* CREATE HEADER */ NSMutableArray *parameterPairs = [NSMutableArray array]; for (NSString *name in standardParameters) { NSString *aPair = [name stringByAppendingFormat:@"=\"%@\"", [standardParameters[name] utf8AndURLEncode]]; [parameterPairs addObject:aPair]; } NSString *oAuthHeader = [@"OAuth " stringByAppendingFormat:@"%@", [parameterPairs componentsJoinedByString:@", "]]; [request setValue:oAuthHeader forHTTPHeaderField:@"Authorization"]; /* REQUEST */ [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { NSString *reponseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"Response string: %@, error: %@", reponseString, error); }];
我得到的回复是“signature_invalid”。 无论如何,我遗漏了与url编码和签名生成相关的部分,因为它们可能占用太多空间。 我想知道我是否在这里犯了错误,或者是否创建签名的实际function有问题。
事实certificate,签名创建部分(HMAC-SHA1)是正确的。 我只需要在执行HTTP请求之前从标头中删除符号,否则OAUTH请求会认为签名与请求本身不匹配。 固定代码:
// this is a convenience function for oauth - (NSData *)fetchDataForURL:(NSString *)url paramPairs:(NSArray *)paramPairs error:(NSError**)error response:(NSHTTPURLResponse**)response timeOut:(float)timeOut { NSMutableString *mutableURL = [[NSMutableString alloc] init]; [mutableURL appendString:url]; int paramPairCount = 0; for (OPTTradeKingParamPair *paramPair in paramPairs) { if (paramPairCount > 0) [mutableURL appendString:@"&"]; [mutableURL appendFormat:@"%@=", paramPair.param]; int argCount = 0; for (NSString *arg in paramPair.args) { if (argCount > 0) [mutableURL appendString:@","]; [mutableURL appendFormat:@"%@", arg]; argCount++; } paramPairCount++; } //NSLog(@"URL request: %@", mutableURL); NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:mutableURL] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:5]; request.HTTPMethod = @"GET"; // oauth fields NSString *oauth_timestamp = [NSString stringWithFormat:@"%lu", (unsigned long)[NSDate.date timeIntervalSince1970]]; NSString *oauth_nonce = [NSString getNonce]; NSString *oauth_consumer_key = @"*****"; NSString *oauth_token = @"*****"; NSString *oauth_signature_method = @"HMAC-SHA1"; NSString *oauth_version = @"1.0"; NSMutableDictionary *standardParameters = [NSMutableDictionary dictionary]; [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"]; NSMutableArray *paramPairKeys = [[NSMutableArray alloc] init]; for (OPTTradeKingParamPair *paramPair in paramPairs) { NSString *key = paramPair.param; NSMutableString *args = [[NSMutableString alloc] init]; int argCount = 0; for (NSString *arg in paramPair.args) { if (argCount > 0) [args appendString:@","]; [args appendFormat:@"%@", arg]; } [standardParameters setValue:args forKey:key]; [paramPairKeys addObject:key]; } NSString *parametersString = CHQueryStringFromParametersWithEncoding(standardParameters, NSUTF8StringEncoding); // use URL and remove ? (always at end of URL) NSString *request_url = [url stringByReplacingOccurrencesOfString:@"?" withString:@""]; NSString *oauth_consumer_secret = @"*****"; NSString *oauth_token_secret = @"*****"; NSString *baseString = [@"GET" stringByAppendingFormat:@"&%@&%@", request_url.utf8AndURLEncode, parametersString.utf8AndURLEncode]; // append oauth token secret to consumer secret NSString *secretString = [oauth_consumer_secret.utf8AndURLEncode stringByAppendingFormat:@"&%@", oauth_token_secret.utf8AndURLEncode]; NSString *oauth_signature = [self.class signClearText:baseString withSecret:secretString]; standardParameters[@"oauth_signature"] = oauth_signature; // remove symbols portion for header before doing request for (NSString* keyToRemove in paramPairKeys) { [standardParameters removeObjectForKey:keyToRemove]; } [standardParameters removeObjectForKey:@"symbols"]; NSMutableArray *parameterPairs = [NSMutableArray array]; for (NSString *name in standardParameters) { NSString *aPair = [name stringByAppendingFormat:@"=\"%@\"", [standardParameters[name] utf8AndURLEncode]]; [parameterPairs addObject:aPair]; } parameterPairs = [NSMutableArray arrayWithArray:[parameterPairs sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)]]; NSString *oAuthHeader = [@"OAuth " stringByAppendingFormat:@"%@", [parameterPairs componentsJoinedByString:@", "]]; [request setValue:oAuthHeader forHTTPHeaderField:@"Authorization"]; NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:response error:error]; [OPTCrashModule addErrorWithData:data error:*error]; return data; }
如何调用代码:
- (DataAPIReturnVal)findInfoForSymbols:(NSArray*)tickerSymbols returnedTickerInfos:(NSMutableArray *)tickerInfos { NSMutableString *symbols = [[NSMutableString alloc] init]; int index = 0; for(NSString *tickerSymbol in tickerSymbols) { if (index > 0) [symbols appendString:@","]; OPTTickerInfo *tickerInfo = [[OPTTickerInfo alloc] init]; [tickerInfo setName:tickerSymbol]; [tickerInfos addObject:tickerInfo]; [symbols appendString:[tickerSymbol uppercaseString]]; index++; } NSMutableArray *paramPairs = [[NSMutableArray alloc] init]; OPTTradeKingParamPair *paramPair = [[OPTTradeKingParamPair alloc] initWithParam:@"symbols" args:@[symbols]]; [paramPairs addObject:paramPair]; DataAPIReturnVal retVal = DataAPIGeneralError; NSHTTPURLResponse *response = nil; NSError *error = nil; NSData * retData = [self fetchDataForURL:@"https://api.tradeking.com/v1/market/ext/quotes.json?" paramPairs:paramPairs error:&error response:&response timeOut:[tickerSymbols count]]; // ....and so on }
Param对只是一个对象数组,其中每个对象都是一个“param”字符串和“args”数组。 Param可以是类似“符号”的东西,“args”可以是实际的符号参数,即fas,faz,msft等。
人们要求的额外东西:
- (NSString *)signClearText:(NSString *)text withSecret:(NSString *)secret { NSData *secretData = [secret dataUsingEncoding:NSUTF8StringEncoding]; NSData *clearTextData = [text dataUsingEncoding:NSUTF8StringEncoding]; unsigned char result[20]; hmac_sha1((unsigned char *)[clearTextData bytes], [clearTextData length], (unsigned char *)[secretData bytes], [secretData length], result); //Base64 Encoding char base64Result[32]; size_t theResultLength = 32; Base64EncodeData(result, 20, base64Result, &theResultLength); NSData *theData = [NSData dataWithBytes:base64Result length:theResultLength]; return [NSString.alloc initWithData:theData encoding:NSUTF8StringEncoding]; }
我需要花一些时间打包代码以供一般使用。 在普通公众可以重复使用它之前,还有很多其他的东西需要排除。