简体   繁体   中英

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

I am trying to request an oAuth token in C# doing exactly what Postman (where it works) is doing, but I keep getting Unauthorized. I can't figure out what Postman is doing differently.

Here is my code below:

        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);

Here is what my settings look like in postman:

在此处输入图像描述

First of all, your issue is that you're using the wrong Encoding when generating your Basic auth header content.

Switch from ASCII to UTF8:

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

Once you solve this issue, you might want to look into making your life easier to actually read the AccessToken from the response. I would recommend using the ReadFromJsonAsync<T> extension method for HttpContent:

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

You'll need the System.Net.Http.Json using statement to get access to the method.

If you still have issues deserializing the Json, the ReadFromJsonAsync<T> method takes JsonSerializerOptions as an optional parameter to help you adjust to your incoming data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM