Matheo
Matheo

Reputation: 35

Basic authentication in HTTP Post request

I am writing a simple HTTP post request which will be sending some data to the server.

Code snippet:

HttpClient client = new HttpClient(); 
var name = _context.Users.FirstOrDefault(u => u.Id == UserId.FirstName) 
var surname = _context.Users.FirstOrDefault(s => s.Id == UserId.LastName) 
var message = new Message 
{
  FirstName = message.FirstName
  LastName = message.LastName
}
var authenticationString = $"{name}:{surname}";
var base64EncodedAuthenticationString= 
Convert.ToBase64String(System.Text.ASCIIEncoding.UTF8.GetBytes(authenticationString));
var content = new StringContent(message.ToString() ?? String.Empty, Encoding.UTF8);
content.Headers.Add("Authorization", "Basic" + base64EncodedAuthenticationString);
var response = await client.PostAsync("https://mywebsite.com", content); 
var responseString = await response.Content.ReadAsStringAsync(); 

And when I am debbuging this code snippet I get exception error which says:

"Misused header name, 'Authorization'. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects."

How to fix that? Without basic authentication I get response 401 (unauthorized) from the service, but I need to get code 200 (ok) and I cannot acheive that without Basic Authentication.

Upvotes: 0

Views: 3147

Answers (3)

Lex
Lex

Reputation: 11

Stop using the PostAsync method in favor of SendAsync method which gives you the full flexibility you need. SendAsync expects a HttpRequestMessage that you can configure to your liking.

var authenticationString = $"{name}:{surname}";
var base64EncodedAuthenticationString = Convert.ToBase64String(Encoding.ASCII.GetBytes(authenticationString);
var content = new StringContent(message.ToString() ?? String.Empty, Encoding.UTF8);

var requestMessage = new HttpRequestMessage
{
    Method = HttpMethod.Post,
    RequestUri = new Uri("https://mywebsite.com"),
    Content = content
};
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Basic", base64EncodedAuthenticationString);

var response = await _httpClient.SendAsync(requestMessage);

Upvotes: 0

Tristan Blackwell
Tristan Blackwell

Reputation: 222

In basic auth you will need a space between Basic and the authentication string. So it will be:

content.Headers.Add("Authorization", "Basic " + base64EncodedAuthenticationString);

Upvotes: 0

Markus
Markus

Reputation: 22436

There are two problems in the code:

  • There should be a space between Basic and the credentials.
  • The code uses the content headers for transmitting the Authorization header; this should be moved to the request headers, e.g. by using the DefaultRequestHeaders property instead:
client.DefaultRequestHeaders.Add(
  "Authorization", 
  "Basic " + base64EncodedAuthenticationString);

Upvotes: 1

Related Questions