Breaking

Tuesday, December 7, 2021

Blazor–Using Basic authentication

For an internal application I’m building I needed to use Basic authentication.

Remark: In case you forgot, Basic Authentication transmits credentials like user ID/password as a base64 encoded string in the Authorization header. This is of course not the most secure way as any man-in-the-middle can capture and read this header data.

If you look around on the Internet, a typical example on how to this in .NET looks like this:

var httpClientHandler = new HttpClientHandler()
{
Credentials = new NetworkCredential("username", "****"),
};
var client = new HttpClient(httpClientHandler);
view raw HttpClient.cs hosted with ❤ by GitHub

We create a HttpClientHandler, set the Credentials and pass it to our HttpClient as a parameter.

Of course it is even better to not create an HttpClient instance yourself but instead use the HttpClientFactory to create a Named or Typed HttpClient.

services.AddHttpClient("ExampleClient", c =>
{
//Add your configuration here
}).ConfigurePrimaryHttpMessageHandler(() =>
{
return new HttpClientHandler()
{
UseDefaultCredentials = true,
Credentials = new NetworkCredential("username","*****"),
};
});

But if you try to use the code above in a Blazor application, you’ll end up with the following runtime error:

System.PlatformNotSupportedException: Property Credentials is not supported.



As the HttpClient implementation for Blazor stays as close as possible to the fetch api the browser, you’ll need to take a different approach and set the authorization header directly:


var client = new HttpClient();
var byteArray = Encoding.UTF8.GetBytes("username:*****");
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
view raw Blazor.cs hosted with ❤ by GitHub

No comments:

Post a Comment