Add Or Change Identity Claims In .Net 8 Blazor Web App

Mahdi Elahi 31 Reputation points
2024-01-16T19:17:43.76+00:00

Hi,
In Create New Blazor Web App Project :
Check => Individual Check => .Net 8 Check => Auto Interactivew and in ApplicationUser.cs I add a property for use full name { public sting Fullname { get; set; } } but in components i want show current user full name , but how to do it ?
how to add custom claims to user and get in view component
for example : i want in component use like this:

  <AuthorizeView>
@Hello @context.User.Identity.Fullname
  </AuthorizeView>
Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,654 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Ping Ni-MSFT 4,815 Reputation points Microsoft Vendor
    2024-01-17T05:17:25.13+00:00

    Hi @Mahdi Elahi,
    Here is a whole working demo:
    Register.razor

     user.Fullname = "Full_"+user.UserName;   //set the fullname, just for easy testing
     var result = await UserManager.CreateAsync(user, Input.Password);
    
     if (!result.Succeeded)
     {
         identityErrors = result.Errors;
         return;
     }
     //add the Fullname claims
     await UserManager.AddClaimAsync(user, new System.Security.Claims.Claim("Fullname", user.Fullname));
    

    Show full name in component:

    @page "/auth"
    
    @using Microsoft.AspNetCore.Authorization
    
    @attribute [Authorize]
    
    @inject AuthenticationStateProvider authenticationStateProvider
    
    <AuthorizeView>
        <Authorized>
            <p>Hello @fullname</p>
        </Authorized>
    
    </AuthorizeView>
    
    @code {
        private string fullname;
    
        protected override async Task OnInitializedAsync()
        {
            var authState = await authenticationStateProvider.GetAuthenticationStateAsync();
            var user = authState.User;
    
            // Get the Fullname claim
            var fullnameClaim = user.FindFirst("Fullname");
    
            if (fullnameClaim != null)
            {
                fullname = fullnameClaim.Value;
            }
        }
    }
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
    Best regards,
    Rena

    1 person found this answer helpful.

  2. Bruce (SqlWork.com) 70,216 Reputation points
    2025-01-21T18:47:20.64+00:00

    your issue is that User (and database access) are only available server side during the static pre-render. in client you use the AuthenticationStateProvider to access user information. any additional information you want must be added as a claim during authentication (see adding custom claims).

    you appear to be using individual, so you are using razor pages to authenticate. you will need to write server middleware that replaces the user principal with one with the additional clams

    https://stackoverflow.com/questions/53292286/is-there-a-way-to-add-claims-in-an-asp-net-core-middleware-after-authentication

    your other option is to create a custom AuthenticationStateProvider that adds the claims:

    https://learn.microsoft.com/en-us/aspnet/core/blazor/security/authentication-state?view=aspnetcore-9.0&pivots=server

    the server state must be persisted to the client:

    https://learn.microsoft.com/en-us/aspnet/core/blazor/security/?view=aspnetcore-9.0&tabs=visual-studio

    server code:

    builder.Services.AddRazorComponents()
        .AddInteractiveWebAssemblyComponents()
        .AddAuthenticationStateSerialization(
            options => options.SerializeAllClaims = true);
    

    client (wasm) code:

    builder.Services.AddAuthorizationCore();
    builder.Services.AddCascadingAuthenticationState();
    builder.Services.AddAuthenticationStateDeserialization();
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.