gpt4 book ai didi

iOS OAuth 签名生成?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:17:04 24 4
gpt4 key购买 nike

我一直在寻找可以为 Oauth header 生成签名的代码,这让我很痛苦。我的目标平台是 iOS,我需要为 TradeKing API 执行此操作。基本上,他们的查询需要 OAuth(无需使用 Oauth 工作流程提前授权我的应用程序供个人使用;我只需要使用 TradeKing 提供给我的 key 使用 oauth header 对每个查询进行签名)。这是一些示例文档:GetPost

我找到的最佳示例代码如下:https://github.com/Christian-Hansen/simple-oauth1

我能够按照他的示例并显示 LinkedIn 图书馆登录信息。然后我修改了 TradeKing REST 查询的代码,但由于签名无效而失败。这让我很担心,因为生成签名的代码是最复杂的部分……而且我不确定我是否正确使用了他的代码。在下面的代码中,我将 oauth key 和 secret 更改为 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 编码和签名生成相关的部分,因为它们可能会占用太多空间。我想知道我是否在这里犯了错误,或者创建签名的实际函数是否有问题。

最佳答案

事实证明,签名创建部分 (HMAC-SHA1) 是正确的。我只需要在执行 HTTP 请求之前从 header 中删除符号,否则 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”字符串和“args”数组。 Param 可以是“symbols”之类的东西,“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];
}

我需要花一些时间打包代码以供一般使用。在公众可以重用它之前,我还必须清除其他一些东西。

关于iOS OAuth 签名生成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26398467/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com