簡體   English   中英

oAuth2 令牌請求使用 C# HttpClient 失敗但在 Postman 中工作

[英]oAuth2 token request failing using C# HttpClient but working in Postman

我正在嘗試在 C# 中請求一個 oAuth 令牌,而這正是 Postman(它工作的地方)正在做的事情,但我一直在未經授權。 我不知道 Postman 有什么不同。

下面是我的代碼:

        var request = new HttpRequestMessage(HttpMethod.Post, "https://myapi/OAuth/Token/")
        {
            Content = new FormUrlEncodedContent(new KeyValuePair<string?, string?>[]
            {
                // new("client_id", _clientId),
                // new("client_secret", _clientSecret),
                // new("scope", "company-api"),
                new ("Content-Type", "application/x-www-form-urlencoded"),
                new("grant_type", "client_credentials")
            })
        };

        _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", System.Convert.ToBase64String(Encoding.ASCII.GetBytes($"{_clientId}:{_clientSecret}")));

        using var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
        response.EnsureSuccessStatusCode();
        await using var responseContentStream = await response.Content.ReadAsStreamAsync();

        var accessToken = await JsonSerializer.DeserializeAsync<AccessToken>(
            responseContentStream, JsonSerializerOptions.Default);

這是我在 postman 中的設置:

在此處輸入圖像描述

首先,您的問題是您在生成 Basic auth header 內容時使用了錯誤的編碼。

從 ASCII 切換到 UTF8:

_httpClient.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Basic",
        System.Convert.ToBase64String(Encoding.UTF8.GetBytes($"{_clientId}:{_clientSecret}")));

解決此問題后,您可能想考慮讓您的生活更輕松,以便從響應中實際讀取 AccessToken。 我建議對 HttpContent 使用ReadFromJsonAsync<T>擴展方法:

var jsonData = await response.Content.ReadFromJsonAsync<AccessToken>();

您需要使用System.Net.Http.Json using 語句來訪問該方法。

如果您在反序列化 Json 時仍然遇到問題, ReadFromJsonAsync<T>方法將JsonSerializerOptions作為可選參數來幫助您調整傳入數據。

暫無
暫無

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

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