How to use Basic Auth with HttpClient?

winanjaya 146 Reputation points
2023-03-07T14:53:59.6366667+00:00

Hi All,

How to use Basic Auth with HttpClient?

I use snippet codes below, but keeps getting 401, what I have missed?

                var authenticationString = $"{userName}:{userPassword}";
                var base64String = Convert.ToBase64String(
                   System.Text.Encoding.ASCII.GetBytes(authenticationString));

                _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", base64String);

                await _httpClient.GetAsync(url);
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,648 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Alexander Bösel 0 Reputation points
    2023-10-26T08:38:14.14+00:00

    Hi, does System.Text.Encoding.UTF8.GetBytes(authenticationString) work for you?

    Cheers,

    Alex

    0 comments No comments

  2. Bruce (SqlWork.com) 61,731 Reputation points
    2023-10-26T16:15:31.98+00:00

    its one of the following issues

    • username & password combo not valid
    • credentials are valid, but user not authorized to access resource
    • basic authentication not supported by server (check the WWW-Authenticate header)
    0 comments No comments