Last active
February 18, 2024 16:11
-
-
Save HammadMaqbool/e9d793e66d9e1c708351efd31fb9daa8 to your computer and use it in GitHub Desktop.
This is the custome user factory class for using with role based authorization in Blazor Apps got this class code from the book "Blazor in action" by Chris Sainty
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.AspNetCore.Components.WebAssembly.Authentication.Internal; | |
using Microsoft.AspNetCore.Components.WebAssembly.Authentication; | |
using System.Security.Claims; | |
using System.Text.Json; | |
namespace {Enter your namespace name here} | |
{ | |
public class CustomUserFactory<TAccount> : AccountClaimsPrincipalFactory<RemoteUserAccount> | |
{ | |
public CustomUserFactory(IAccessTokenProviderAccessor accessor) : base(accessor) { } | |
public override async ValueTask<ClaimsPrincipal> CreateUserAsync(RemoteUserAccount account,RemoteAuthenticationUserOptions options) | |
{ | |
var initialUser = await base.CreateUserAsync(account, options); | |
if (initialUser?.Identity?.IsAuthenticated ?? false) | |
{ | |
var userIdentity = (ClaimsIdentity)initialUser.Identity; | |
account.AdditionalProperties.TryGetValue(ClaimTypes.Role, out var roleClaimValue); | |
if (roleClaimValue is not null && roleClaimValue is JsonElement element && element.ValueKind == JsonValueKind.Array) | |
{ | |
userIdentity.RemoveClaim(userIdentity.FindFirst(ClaimTypes.Role)); | |
var claims = element.EnumerateArray() | |
.Select(x => new Claim(ClaimTypes.Role, x.ToString())); | |
userIdentity.AddClaims(claims); | |
} | |
} | |
return initialUser ?? new ClaimsPrincipal(); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Code to set user role in Auth0 for blazorApp | |
exports.onExecutePostLogin = async (event, api) => { | |
const roleClaim = 'http://schemas.microsoft.com/ws/2008/06/identity/claims/role'; | |
if (event.authorization) { | |
api.idToken.setCustomClaim(roleClaim, event.authorization.roles); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment