oauth - 如何生成 OAuth1.0 签名
问题描述
我必须使用OAuth1.0
. 在响应头中,它需要访问令牌、OAuth Nonce、时间戳和 OAuthSignature。我编写了创建方法 Timestamp
以及 OAuthNonce
如何使用这些参数生成 OAuthsignature?它使用 HMAC-SHA1 方法对签名进行哈希处理。如何创建生成 OAuth 签名密钥的方法。任何人都可以建议使用这些参数创建签名的方法吗?提前致谢。
private static string CreateOAuthTimestamp()
{
var nowUtc = DateTime.UtcNow;
var timeSpan = nowUtc - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
var timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
return timestamp;
}
private string CreateOauthNonce()
{
return Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
}
解决方案
我找到了一个创建 Oauth 1.0 签名的方法。它需要 api 请求的所有参数在 SHA1 算法中进行散列。
private string CreateOauthSignature
(string resourceUrl, string oauthNonce, string oauthTimestamp ,
SortedDictionary<string, string> requestParameters)
{
//Add the standard oauth parameters to the sorted list
requestParameters.Add("oauth_consumer_key", consumerKey);
requestParameters.Add("oauth_nonce", oauthNonce);
requestParameters.Add("oauth_signature_method", OauthSignatureMethod);
requestParameters.Add("oauth_timestamp", oauthTimestamp);
requestParameters.Add("oauth_token", accessToken);
requestParameters.Add("oauth_version", OauthVersion);
var sigBaseString = requestParameters.ToWebString();
var signatureBaseString = string.Concat
("GET", "&", Uri.EscapeDataString(resourceUrl), "&",
Uri.EscapeDataString(sigBaseString.ToString()));
//Using this base string, encrypt the data using a composite of the
//secret keys and the HMAC-SHA1 algorithm.
var compositeKey = string.Concat(Uri.EscapeDataString(consumerKeySecret), "&",
Uri.EscapeDataString(accessTokenSecret));
string oauthSignature;
using (var hasher = new HMACSHA1(Encoding.ASCII.GetBytes(compositeKey)))
{
oauthSignature = Convert.ToBase64String(
hasher.ComputeHash(Encoding.ASCII.GetBytes(signatureBaseString)));
}
return oauthSignature;
}
ToWebstring() 是一种扩展方法,用于将排序字典转换为 Web 字符串并对特殊字符进行编码。创建签名后,可以将其与其他标头参数一起包含在 Http 请求的授权标头中。随机数、时间戳、访问令牌等。
推荐阅读
- flutter - 如何将字符串列表存储到 Firestore?
- git - VSCode 中的活动更改过多
- julia - 贝叶斯 ODE 与 Julia
- java - 如何在 Spring Boot 中检索 url 并在 Angular 中使用它?
- firebase - Firebase 您的 Cloud Firestore 数据库对基本安全规则有不安全的规则
- mongoexport - 使用 mongoexport 从特定时间范围内使用查询和时间戳从 mongodb 导出数据
- html - 在相同大小的单元格中显示具有不同高度和宽度的图像
- angular - 单角反应形式的两个独立验证
- javascript - 网络元素突然消失
- macos - Zsh 外壳别名