I'm using AddOidcAuthentication for user login in the client App of my Blazor application. After successful login, I'm attempting to fetch data and set the user role in the identity. However, I'm encountering an issue where the role is not being properly set in the identity, causing problems when trying to check roles on the server side of Blazor.
Below is the code snippet I've tried to set the role in the identity using claims:
var existingClaims = _authenticationState.User.Claims.ToList();existingClaims.Add(new Claim(ClaimTypes.Role, "Admin"));var identity = new ClaimsIdentity(existingClaims, null);var updatedUser = new ClaimsPrincipal(identity);_authenticationState = new AuthenticationState(updatedUser);
When attempting to fetch the role in the client app, the claim value is successfully obtained using the following code:
var currentAuthState1 = await _authenticationStateProvider.GetAuthenticationStateAsync();var claimValue = currentAuthState1.User.Identity.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email)?.Value;
However, when checking roles on the server side using a custom filter, the role is coming up as null. Here's the code for the custom filter:
public class RoleAuthorizationFilter : Attribute, IAsyncAuthorizationFilter{ private readonly string _requiredRole; public RoleAuthorizationFilter(string requiredRole) { _requiredRole = requiredRole; } public async Task OnAuthorizationAsync(AuthorizationFilterContext context) { var authenticationStateProvider = context.HttpContext.RequestServices.GetService(typeof(AuthenticationStateProvider)) as AuthenticationStateProvider; ClaimsIdentity claimsIdentity1 = context.HttpContext.User.Identity as ClaimsIdentity; string _role = claimsIdentity1.FindFirst(ClaimTypes.Role).Value; var claimsIdentity = context.HttpContext.User.Identity as ClaimsIdentity; Claim? claim = claimsIdentity?.FindFirst(ClaimTypes.Role); var value = claim.Value; var authState = await authenticationStateProvider.GetAuthenticationStateAsync(); var user = authState.User; if (!user.Identity.IsAuthenticated) { context.Result = new RedirectToRouteResult("login", null); return; } if (!user.IsInRole(_requiredRole)) { context.Result = new ForbidResult(); return; } }}
I'm not sure why the above code is not updating the token or if there's another issue causing the role to be null on the server side. Any insights or suggestions would be greatly appreciated. Thank you!
Code that i have tried added in above details