Wolf Donner
Wolf Donner

Reputation: 195

Windows Authentication using Blazor with .Net Core WebApi

I have the task to develop a Blazor Webassembly App. This app is only used within the companys network and for security reasons we would like to use the existing AD and NTLM Authentication.

So far I have a minimal Blazor App configured and running in IIS. Its configured to use Windows Authentication and that works so far. When I open the app in Browser I get asked for my credentials. The app should also communicate with a .net core webapi which is also secured by windows authentication. This webapi security too works as it should. When I open an URL to it in Browser I get asked for my credentials and the page loads as it should.

Now the Problem: When I call the same url (that works in Browser) from my Blazor app with HttpClient.GetAsync I get an "401: Not Authorized" error. Even though the app itself is loaded with the same authentication. Is there something I have to do? The MSDN Documenations a gigantic and I couldnt find a Solution.

In the WebApi Startup.cs in ConfigureServices() I added

services.AddAuthentication(IISDefaults.AuthenticationScheme);
services.AddAuthorization();

and in Configure()

app.UseCors(x => x.AllowAnyMethod().AllowAnyHeader().SetIsOriginAllowed(origin => true).AllowCredentials());
app.UseAuthentication();
app.UseAuthorization();

PS: The Blazor App uses .NET Core 3.1 The WebApi uese .NET 5.0

Upvotes: 2

Views: 4894

Answers (1)

JanB
JanB

Reputation: 308

I recommend checking Blazor WebAssembly additional security scenarios (all the examples are there)

To authorize your request, you can use HttpClient with BaseAddressAuthorizationMessageHandler:

builder.Services.AddHttpClient("ServerAPI", 
    client => client.BaseAddress = new Uri("https://www.example.com/base"))
.AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();

BaseAddressAuthorizationMessageHandler will automatically add Authorize header to all outgoing requests.

Note: This works only with Blazor Wasm, not Server.

Upvotes: 0

Related Questions