不幸的是,电子贸易 API 文档不是很清楚,而且我很难为 OAuth 身份验证生成有效签名。我正在使用 .NET 5(核心)。
这是我得到的:
HTTP Status 401 - oauth_problem=signature_invalid
有谁生成签名的规范是什么?
这是我尝试过的:
private static string GetSignatureBaseString(string strUrl, string TimeStamp,
string Nonce, string strConsumer, string strOauthToken, SortedDictionary<string, string> data)
{
//1.Convert the HTTP Method to uppercase and set the output string equal to this value.
string Signature_Base_String = "GET";
Signature_Base_String = Signature_Base_String.ToUpper();
//2.Append the ‘&’ character to the output string.
Signature_Base_String = Signature_Base_String + "&";
//3.Percent encode the URL and append it to the output string.
string PercentEncodedURL = Uri.EscapeDataString(strUrl);
Signature_Base_String = Signature_Base_String + PercentEncodedURL;
//4.Append the ‘&’ character to the output string.
Signature_Base_String = Signature_Base_String + "&";
//5.append OAuth parameter string to the output string.
var parameters = new SortedDictionary<string, string>
{
{"oauth_consumer_key", strConsumer},
{"oauth_timestamp", TimeStamp},
{"oauth_nonce", Nonce},
{"oauth_signature_method", "HMAC-SHA1"},
{"oauth_callback", "oob"},
{"oauth_version", "1.0"}
};
bool first = true;
foreach (KeyValuePair<string, string> elt in parameters)
{
if (first)
{
Signature_Base_String = Signature_Base_String + Uri.EscapeDataString(elt.Key + "=" + elt.Value);
first = false;
}
else
{
Signature_Base_String = Signature_Base_String + Uri.EscapeDataString("&" + elt.Key + "=" + elt.Value);
}
}
return Signature_Base_String;
}
private static string GetSha1Hash(string key, string baseString)
{
var encoding = new System.Text.ASCIIEncoding();
byte[] keyBytes = encoding.GetBytes(key);
byte[] messageBytes = encoding.GetBytes(baseString);
string strSignature = string.Empty;
using (HMACSHA1 SHA1 = new HMACSHA1(keyBytes))
{
var Hashed = SHA1.ComputeHash(messageBytes);
strSignature = Convert.ToBase64String(Hashed);
}
return strSignature;
}
这就是我如何打一个非常基本的电话:
TimeSpan t = DateTime.UtcNow - new DateTime(1970, 1, 1);
int secondsSinceEpoch = (int)t.TotalSeconds;
var nonce = "kllo9940pd9333jh";
var baseString = GetSignatureBaseString("https://api.etrade.com/oauth/request_token", secondsSinceEpoch.ToString(), nonce.ToString(), "XXX", string.Empty, null);
var signature = GetSha1Hash("XXX", baseString);
var headers = "OAuth realm=,oauth_callback=\"oob\",oauth_signature=\"" + HttpUtility.UrlEncode(signature) + "\",oauth_nonce=\"" + nonce + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_consumer_key=\"XXX\",oauth_timestamp=\"" + secondsSinceEpoch.ToString() + "\"";
using (var http = new HttpClient())
{
http.DefaultRequestHeaders.Add("Authorization", headers);
var httpResponse = http.GetAsync("https://api.etrade.com/oauth/request_token").Result;
var httpContent = httpResponse.Content.ReadAsStringAsync().Result;
return httpContent;
}
不幸的是,到目前为止,我没有尝试过任何工作。感谢任何帮助。