如何解决如何为这里的 api c# 生成 Oauth1.0 的签名
我想将不记名令牌的访问令牌请求发送到这里 api.(https://developer.here.com/tutorials/how-to-authenticate-with-here-oauth/) 他们展示了使用节点的示例。但是我在 c# 中尝试了相同的方法。但是我收到了 400 个错误的请求。我的代码如下:
var url = "https://account.api.here.com/oauth2/token";
String id = "key id";
String secret = "key secret";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Method = "POST";
var timeStamp = ((int)(DateTime.UtcNow - new DateTime(1970,1,1)).TotalSeconds).ToString();
var nonce = Convert.ToBase64String(Encoding.UTF8.GetBytes(timeStamp));
var signatureBaseString = Escape(httpWebRequest.Method.toupper()) + "&";
signatureBaseString += url.ToLower() + "&";
signatureBaseString +=
"oauth_consumer_key=" + id + "&" +
"oauth_nonce=" + nonce + "&" +
"oauth_signature_method=" + "HMAC-SHA1" + "&" +
"oauth_timestamp=" + timeStamp + "&" +
"oauth_version=" + "1.0";
var key = secret;
var signatureEncoding = new ASCIIEncoding();
var keyBytes = signatureEncoding.GetBytes(key);
var signatureBaseBytes = signatureEncoding.GetBytes(signatureBaseString);
string signatureString;
using (var hmacsha1 = new HMACSHA1(keyBytes))
{
var hashBytes = hmacsha1.ComputeHash(signatureBaseBytes);
signatureString = Convert.ToBase64String(hashBytes);
}
string SimpleQuote(string s) => '"' + s + '"';
var header =
"Content-Type=application/x-www-form-urlencoded" + "," +
"Authorization=OAuth" + "," +
"oauth_consumer_key=" + SimpleQuote(id) + "," +
"oauth_nonce=" + SimpleQuote(nonce) + "," +
"oauth_signature_method=" + SimpleQuote("HMAC-SHA1") + "," +
"oauth_timestamp=" + SimpleQuote(timeStamp) + "," +
"oauth_version=" + SimpleQuote("1.0") + "," +
"oauth_signature= " + SimpleQuote(signatureString);
httpWebRequest.Headers.Add(HttpRequestHeader.Authorization,header);
string postData = "grant_type=client_credentials";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] byte1 = encoding.GetBytes(postData);
httpWebRequest.ContentLength = byte1.Length;
var newStream = httpWebRequest.GetRequestStream(); // get a ref to the request body so it can be modified
newStream.Write(byte1,byte1.Length);
newStream.Close();
var response = httpWebRequest.GetResponse();
可能是我以错误的方式生成签名。但是我只有密钥 ID 和秘密,并且我设法实现了这一点。请帮我指出我犯的错误。
解决方法
你能看看下面的文章吗? Getting (401) UnAuthorized error on some requests not all,but most 尝试使用不同的库,例如 HttpClient 或 RestClient。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。