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,602 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Ping Ni-MSFT 4,720 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


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.