为什么我的OAuth签名在通过C#中的OAuth1.0连接到WordPress时不匹配



我正在尝试完成OAuth 1.0身份验证过程中的第一步,并检索未经授权的请求令牌。

我一直收到一个401 OAuth签名与WordPress的错误不匹配。我知道问题出在我哈希签名的方式上,因为当我使用Postman时,我计算的签名与Postman计算的签名不同。此外,我可以通过Postman成功检索和未经授权的请求令牌。

我在计算哈希时哪里出错了?我正在使用HMAC-SHA1。

private void AuthorizeWP()
{
string requestURL = @"http://mywordpressurl.com/oauth1/request";
UriBuilder tokenRequestBuilder = new UriBuilder(requestURL);
var query = HttpUtility.ParseQueryString(tokenRequestBuilder.Query);
query["oauth_consumer_key"] = "myWordPressKey";
query["oauth_nonce"] = Guid.NewGuid().ToString("N");
query["oauth_signature_method"] = "HMAC-SHA1";
query["oauth_timestamp"] = (Math.Truncate((DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds)).ToString();
string signature = string.Format("{0}&{1}&{2}", "GET", Uri.EscapeDataString(requestURL), Uri.EscapeDataString(query.ToString()));
string oauth_Signature = "";
using (HMACSHA1 hmac = new HMACSHA1(Encoding.ASCII.GetBytes("myWordPressSecret")))
{
byte[] hashPayLoad = hmac.ComputeHash(Encoding.ASCII.GetBytes(signature));
oauth_Signature = Convert.ToBase64String(hashPayLoad);
}
query["oauth_signature"] = oauth_Signature;
tokenRequestBuilder.Query = query.ToString();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(tokenRequestBuilder.ToString());
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
}

我现在意识到我做错了什么。

使用OAuth 1.0,当您为哈希密钥生成字节时,您必须将消费者/客户端机密和令牌与"&"连接起来在中间,即使您没有令牌

来源:https://oauth1.wp-api.org/docs/basics/Signing.html

所以在我上面的代码中:

using (HMACSHA1 hmac = new HMACSHA1(Encoding.ASCII.GetBytes("myWordPressSecret")))

需要:

using (HMACSHA1 hmac = new HMACSHA1(Encoding.ASCII.GetBytes("myWordPressSecret&"))

最新更新