簡體   English   中英

由於無效的 OAuth 簽名而涉及查詢參數時,GET 失敗並顯示 401(未經授權)

[英]GET fails with 401 (Unauthorized) when query parameter is involved due to invalid OAuth signature

我正在查詢使用 OAuth1 的 API。 我可以使用 RestSharp 成功進行查詢:

var client = new RestClient("https://api.thirdparty.com/1/");
client.Authenticator = 
    OAuth1Authenticator.ForAccessToken(appKey, appSecret, token, tokenSecret);

var request = new RestRequest("projects/12345/documents", Method.GET);
request.AddParameter("recursive", "true");

var response = client.Execute(request);

不幸的是,我無法在實際項目中使用 RestSharp(我只是在此處使用它來驗證 API 調用是否有效),因此我嘗試僅使用普通的 .NET 來讓 OAuth 正常工作。

我讓它處理不使用查詢參數的請求,所以直接GEThttps://api.thirdparty.com/1/projects/12345/documents工作得很好。

一旦我嘗試使用如 RestSharp 示例中所示的https://api.../documents?recursive=true查詢參數,我就會收到401 Unauthorized錯誤,因為我認為我的 OAuth 簽名無效。

這是我生成 OAuth 簽名和請求的方式。 有人能告訴我在涉及查詢參數時如何生成有效簽名嗎?

static string appKey = @"e8899de00";
static string appSecret = @"bffe04d6";
static string token = @"6e85a21a";
static string tokenSecret = @"e137269f";
static string baseUrl = "https://api.thirdparty.com/1/";
static HttpClient httpclient;
static HMACSHA1 hasher;
static DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

static void Main(string[] args)
{
    // SETUP HTTPCLIENT
    httpclient = new HttpClient();
    httpclient.BaseAddress = new Uri(baseUrl);
    httpclient.DefaultRequestHeaders.Accept.Clear();
    httpclient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    // SETUP THE HASH MESSAGE AUTHENTICATION CODE (HMAC) WITH SHA1
    hasher = new HMACSHA1(new ASCIIEncoding().GetBytes(string.Format("{0}&{1}", appSecret, tokenSecret)));

    // WORKS IF QUERY PARAMETER IS MISSED OFF THE END, FAILS WITH 401 IF INCLUDED
    var document = 
        Request(HttpMethod.Get, "projects/12345/documents?recursive=true");
}

static string Request(HttpMethod method, string url)
{
    // CREATE A TIMESTAMP OF CURRENT EPOCH TIME
    var timestamp = (int)((DateTime.UtcNow - epoch).TotalSeconds);

    // DICTIONARY WILL HOLD THE KEY/PAIR VALUES FOR OAUTH
    var oauth = new Dictionary<string, string>();
    oauth.Add("oauth_consumer_key", appKey);
    oauth.Add("oauth_signature_method", "HMAC-SHA1");
    oauth.Add("oauth_timestamp", timestamp.ToString());
    oauth.Add("oauth_nonce", "nonce");
    oauth.Add("oauth_token", token);
    oauth.Add("oauth_version", "1.0");

    // GENERATE OAUTH SIGNATURE
    oauth.Add("oauth_signature", GenerateSignature(method.ToString(), string.Concat(baseUrl, url), oauth));

    // GENERATE THE REQUEST
    using (var request = new HttpRequestMessage())
    {
        // URL AND METHOD
        request.RequestUri = new Uri(string.Concat(baseUrl, url));
        request.Method = method;

        // GENERATE AUTHORIZATION FOR THIS REQUEST
        request.Headers.Add("Authorization", GenerateOAuthHeader(oauth));

        // MAKE REQUEST
        var response = httpclient.SendAsync(request).Result;

        // ENSURE IT WORKED
        response.EnsureSuccessStatusCode(); // THROWS 401 UNAUTHORIZED

        // RETURN CONTENT
        return response.Content.ReadAsStringAsync().Result;
    };
}

static string GenerateSignature(string verb, string url, Dictionary<string, string> data)
{
    var signaturestring = string.Join(
        "&",
        data
            .OrderBy(s => s.Key)
            .Select(kvp => string.Format(
                    "{0}={1}",
                    Uri.EscapeDataString(kvp.Key), 
                    Uri.EscapeDataString(kvp.Value))
                    )
    );

    var signaturedata = string.Format(
        "{0}&{1}&{2}",
        verb,
        Uri.EscapeDataString(url),
        Uri.EscapeDataString(signaturestring.ToString())
    );

    return Convert.ToBase64String(hasher.ComputeHash(new ASCIIEncoding().GetBytes(signaturedata.ToString())));
}

static string GenerateOAuthHeader(Dictionary<string, string> data)
{
    return "OAuth " + string.Join(
        ", ",
        data
            .Select(kvp => string.Format("{0}=\"{1}\"", Uri.EscapeDataString(kvp.Key), Uri.EscapeDataString(kvp.Value)))
            .OrderBy(s => s)
    );
}

在 oauth 1 中,查詢字符串參數(以及 POST 參數,以防您使用x-www-form-urlencoded POST,因此它們就像正文中的“a=1&b=2”)應包含在鍵值對列表中然后排序並簽名。 因此,要獲得正確的簽名,您必須:

  • 提取所有查詢字符串(和 POST,如上)參數作為鍵值對
  • 從 url 中刪除查詢字符串
  • 像您現在所做的那樣簽署所有內容(沒有查詢字符串的 url,以及所有密鑰對,包括上面提取的和特定於 oauth 的)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM