Home > Net >  Basic authentication in HTTP Post request
Basic authentication in HTTP Post request

Time:07-29

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.

CodePudding user response:

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

CodePudding user response:

In basic auth you will need a space between Basic and the authentication string. So it will be content.Headers.Add("Authorization", "Basic " base64EncodedAuthenticationString);

  • Related