0
votes

I'm trying to get a custom property in the default template of Blazor WebAssembly 3.2, but when I debug the context.User.Identity.Name at the blazor.server part it is null. I can see the user is context.User.Identity.IsAUthenticated is true, but all the other properties seem null or empty.

So to reproduce:

  1. Create a new Blazor WebAssembly 3.2 project
  2. Do the add-migration inital + database-update
  3. Start the blazor.server project and register a user and login
  4. Set a breakpoint on the Get method of the Weatherforecast.
  5. The context.User.Identity.Name is empty

Anyone got a guide for this, or a hint where to look. Thanks

1
Take look at this blog google.com/amp/s/code-maze.com/… there is explaned how to store and retrive user claims in token and how to extend user - adopilot
Well the problem is in the Weatherforecasecontroller.cs. I need the username there. When I look at the Httpcontext.User.Name it’s empty. The only thing that I see is: IsAuthenticated = true. What I’m trying to do is: get a username in the controller and then use the usermanager.findasync(username); – - Zero

1 Answers

2
votes

Note: The template stores the email in both the email and the name field in the database.

In Startup.cs in the server. Add these options to AddApiAuthorization.

 services.AddIdentityServer()        
    .AddApiAuthorization<ApplicationUser, ApplicationDbContext>(options =>
    {
        options.IdentityResources["openid"].UserClaims.Add("name");
        options.ApiResources.Single().UserClaims.Add("name");                 
    });

In your controller

Public async Task<IEnumerable<WeatherForecast>> Get()
{
    var userName = User.Identity.Name;
    var applicationUser = await userManager.FindByNameAsync(userName);
...