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

Time:01-08

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:

enter image description here

CodePudding user response:

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.

  • Related