我尝试使用HMAC-SHA1(没有令牌详细信息)来实现Oauth 1.0。调试时,它总是返回以下异常“远程服务器返回错误:(401)未经授权”。但同样的凭证在Postman中运行良好。
我有令牌秘密
var key = EscapeUriDataStringRfc3986(consumerSecret) + "&";"
同时形成关键细节。
try
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Method = "GET";
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 += EscapeUriDataStringRfc3986(url.ToLower()) + "&";
signatureBaseString += EscapeUriDataStringRfc3986(
"oauth_consumer_key=" + EscapeUriDataStringRfc3986(consumerKey) + "&" +
"oauth_nonce=" + EscapeUriDataStringRfc3986(nonce) + "&" +
"oauth_signature_method=" + EscapeUriDataStringRfc3986("HMAC-SHA1") + "&" +
"oauth_timestamp=" + EscapeUriDataStringRfc3986(timeStamp) + "&" +
"oauth_version=" + EscapeUriDataStringRfc3986("1.0"));
//MessageBox.Show(@"signatureBaseString: " + signatureBaseString);
var key = EscapeUriDataStringRfc3986(consumerSecret) + "&";
MessageBox.Show(@"key: " + key);
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);
}
signatureString = EscapeUriDataStringRfc3986(signatureString);
MessageBox.Show(@"signatureString: " + signatureString);
var header =
"oauth_consumer_key=" + SimpleQuote(consumerKey) + "," +
"oauth_nonce=" + SimpleQuote(nonce) + "," +
"oauth_signature_method=" + SimpleQuote("HMAC-SHA1") + "," +
"oauth_timestamp=" + SimpleQuote(timeStamp) + "," +
"oauth_version=" + SimpleQuote("1.0") + "," +
"oauth_signature= " + SimpleQuote(signatureString);
MessageBox.Show(@"header: " + header);
httpWebRequest.Headers.Add(HttpRequestHeader.Authorization, header);
var response = httpWebRequest.GetResponse();
var characterSet = ((HttpWebResponse)response).CharacterSet;
var responseEncoding = characterSet == ""
? Encoding.UTF8
: Encoding.GetEncoding(characterSet ?? "utf-8");
var responsestream = response.GetResponseStream();
if (responsestream == null)
{
//throw new ArgumentNullException(nameof(characterSet));
}
using (responsestream)
{
var reader = new StreamReader(responsestream, responseEncoding);
var result = reader.ReadToEnd();
Console.WriteLine(@"result: " + result);
}
}
catch (Exception ex)
{
MessageBox.Show("Error:"+ex.Message.ToString());
}