Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can "Blazor (ASP.NET Core hostd)" use windows authentication?

I'm developing a Blazor (ASP.NET Core hosted) project and hosted on IIS.

Back the day when I use ASP.NET core 2.2 with razor page, it can use windows authentication.

However with dotnet core 3.0, only Blazor server-side project template has windows authentication option to choose.

But what about the Blazor (ASP.NET Core hosted) project template? From my understanding, it's just like Blazor client-side + dotnet core MVC backend. I don't understand why there's no "windows authentication" option for it.

like image 201
howardgod Avatar asked Jul 22 '19 07:07

howardgod


Video Answer


2 Answers

In Blazor WebAssembly apps, user authentication and authorization must be handled by the back end web Api, because all client-side code can be modified by users.

Your ASP.NET Core Api can use the Windows authentication and keep track of the authentication state in a cookie. In Blazor WebAssembly you can implement an AuthenticationStateProvider which calls your web Api to get details about the authentication state of the user.

Then you can use the AuthorizeView component to show or hide content depending on the users log on state.

A clear description you can find in Blazor Prepare for Authorization

Source code example in https://github.com/Forestbrook/BlazorAuthorizationExample.

like image 159
Marcel W Avatar answered Oct 03 '22 22:10

Marcel W


There are 2 problems to solve.

For the webassembly, use the solution with the AuthenticationStateProvider to get the user authenticated and do a call to the api (enable windows authentication and disable anonymous login) that returns the windows username and the authorization roles, if you use them for authorization. Load the roles into client side identity as claims and the webassembly is set up for authentication & authorization.

Because all code is run in the webassembly, you should also protect the serverside api controller actions with authorization attributes, except for the call that identifies the user to the wasm.

Enable authentication and authorization on the server api and use the IClaimsTransformation to modify claims for the authenticated user. When configured correctly, you can use authorization attributes on the controllers too, securing the api.

You can implement StateContainers on both sides to cache user information so you don't have to read the database for the same info on every action. I use a singleton for that, with a retention time of 5 minutes. You may then update the timestamp on every cache read so you effectively call the database only once.

like image 37
bonensoep Avatar answered Oct 03 '22 22:10

bonensoep