You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#实现OAuth返回invalid Oauth_signature但Postman可正常调用

我查了大量文章、实现方案,也搜了全网,就是找不到有效解决办法,肯定是在SIGNATURE环节漏了某个简单细节。

场景
  • 开发自动化工具:先获取对话ID,再检查API响应状态,根据状态执行后续操作(如发送通知)。
问题

同一API在Postman中可正常调用,但用C# .NET实现时,始终返回签名无效错误,尝试过多种代码和库都无法解决。

错误信息
{"code":"0005","debugMessage":"The server will not process the request because it is unauthenticated. Reason: oauth_problem=signature_invalid&oauth_problem_advice=the oauth_signature is invalid"}
调用函数代码
string domainUrl = @"https://xyz-my-server-domain.com/";
string accountId = "XXXXXXXX";
string appKey = "05119901595a443d8XXXXXXXXX";
string appSecret = "54fdc15a0fXXXXXX";
string token = "ae4e2979958b401c97XXXXXXXXXX";
string tokenSecret = "4b075XXXXXXXXXXXX";


Uri uri = new Uri(domainUrl + @"/conversations/conversation/search");
OAuthBase oauthBase = new OAuthBase();
string nonce = oauthBase.GenerateNonce();
string timeStamp = oauthBase.GenerateTimeStamp();
string authSignature = "";


/// <summary>
/// 看起来都没问题,但肯定哪里出错了...
/// </summary>
string encodedUrl = GetOAuthSignature(uri, appKey, appSecret, token, tokenSecret, timeStamp, nonce, out authSignature);


var client = new RestClient(encodedUrl);
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
var body = @"{ ..... 我的请求体内容 ..... }";
request.AddParameter("application/json", body, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
GetOAuthSignature函数代码
private static string GetOAuthSignature(Uri uri, string consumerKey, string consumerSecret, string token, string tokenSecret, string timeStamp, string nonce, out string signature)
{
    OAuthBase oAuth = new OAuthBase();

    string normalizedUrl = "";
    string normalizedRequestParameters = "";

    /// <summary>
    /// 该API仅允许HMAC-SHA256和HMAC-SHA1签名方法
    /// </summary>
    string signatureStr = oAuth.GenerateSignature(uri, consumerKey, string.Empty, token, string.Empty, "POST", timeStamp, nonce, OAuthBase.SignatureTypes.HMACSHA1, out normalizedUrl, out normalizedRequestParameters);

    signatureStr = HttpUtility.UrlEncode(signatureStr);

    StringBuilder sb = new StringBuilder(uri.ToString());
    sb.AppendFormat("?oauth_consumer_key={0}&", consumerKey);
    sb.AppendFormat("oauth_token={0}&", token);

    /// <summary>
    /// 该API仅允许HMAC-SHA256和HMAC-SHA1签名方法
    /// </summary>
    sb.AppendFormat("oauth_signature_method={0}&", "HMAC-SHA1");
    sb.AppendFormat("oauth_timestamp={0}&", timeStamp);
    sb.AppendFormat("oauth_nonce={0}&", nonce);
    sb.AppendFormat("oauth_version={0}&", "1.0");
    sb.AppendFormat("oauth_signature={0}", signatureStr);

    signature = signatureStr;

    return sb.ToString();
}

我怀疑问题出在GetOAuthSignature函数中。

内容的提问来源于stack exchange,提问作者imk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 01:05:28