Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

How to authenticate and authorize in blazor

$
0
0

Edit: I Answerd myself on this post. Its updated.

I authenticate users using the Windows Authenticate from Blazor. Now I want to authorize these users as well, I do this by having the users roll and userId in a database table that looks like this:

UserIdRoleId
31
71
1121
42
72
82

The actual authorization happens in the CustomAuthenticationStateRrovider.cs

using Microsoft.AspNetCore.Components.Authorization;using System.Diagnostics;using System.Security.Claims;namespace Authtest.Services{    public class CustomAuthenticationStateProvider : AuthenticationStateProvider    {        private List<UserRoles> userRoles = default!;        public override async Task<AuthenticationState> GetAuthenticationStateAsync()        {            var userroleService = new UserRoleService();            userRoles = userroleService.GetUserRolesListe();            var identity = new ClaimsIdentity();            foreach (var role in userRoles)            {                Debug.WriteLine($"Adding role {role.RoleId} to identity.");                identity.AddClaim(new Claim(ClaimTypes.Role, role.RoleId.ToString()));            }            var user = new ClaimsPrincipal(identity);            return new AuthenticationState(user);        }    }}

As you can see in the screenshot the Database query works.Debug var user

The following problem I have now and that is in the index.razor as seen on the 2nd screenshot problem with auth, the Authorized part is displayed although my user has the role 1 and only users with the role 2 should see the text. A Different problem (which depends on the same solution I think) with the LoginDisplay.razor is why always the NotAuthorized part is displayed.

PS: I think the problem is that by creating a new ClaimsPrincipal I override the Windows authentication.

I made a brand new syncfusion blazor server application and put only the authentication part from my project in the new one, so I could try everything out, but nothing worked.

Edit: I even made a more detailed Screenshot from the user variable here.


Viewing all articles
Browse latest Browse all 4839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>