Home > database >  How to implement Custom Authorization in Blazor Server
How to implement Custom Authorization in Blazor Server

Time:06-04

I would like to bypass AspnetCore identity completely, and instead use a custom method of Authenticating the current user.

However, I would still like the existing Authorization framework to work. In other words, I want to be able to use the AuthorizeView and @attribute [Authorize] to maintain security.

I have searched and searched but am not finding any details on how to implement this.

CodePudding user response:

Indeed, all the information is quite fragmented in the documentation. That's why I created this example.

https://github.com/iso8859/AspNetCoreAuthMultiLang

At the end of file myServerAuthenticationStateProvider.cs you can play with roles.

result = new AuthenticationState(
                new ClaimsPrincipal(
                    new ClaimsIdentity(new[] { 
                        new Claim(ClaimTypes.Name, m_login),
                        new Claim(ClaimTypes.Role, "demo_role"),
                        new Claim(ClaimTypes.Role, "Admin"),
                    }, "PutAppNameHere"
            )));

CodePudding user response:

I have searched and searched but am not finding any details on how to implement this

You have to know what to look for.

Anyhow, you can authenticate your users, as for instance, through OpenIdConnect via IdentityServer4 (or later version, I think it is called Duende).

Jwt token authentication is very common... Your App (A Web API end point dedicated for this) may issue the token when a user authenticates, pass it to the Server app, and store it in the local storage. The Jwt token may contain various claims, such as user id, email, and other information which constitues the user's profile.

You would also have to implement the AuthenticationStateProvider object to provide the CascadingAuthenticationState component (embedded in the App component) with data that is cascaded down to components such as AuthorizeView. This is simply done by parsing the Jwt Token into a ClaimsPrincipal object that is provided by the AuthenticationStateProvider object. Go ahead, do that.

Note: Regarding the built-in Authorization feature of Asp.Net and Blazor, you continue to use them as usual, as for instance: @attribute [Authorize]. If the user is authenticated, then, by default, he's authorized to view the protected resource, unless you want to authorize only users belonging to a given roles, having given claims, or you use policy-based authorization. But that's not something you'll have to deal with as it universal to all manners of authentications...

May I ask why don't you want to use AspnetCore identity ?

I believe this answer may help you in understanding how things are connected with each other, and how I've created various components that interact with each other. Note that there are other similar answers by me, but you'll have to look for them.

  • Related