UserManager.GetUserAsync returns null when using the default Blazor WebAssembly template.
I'm using Blazor WebAssembly with Authentication (Indivual User Accounts, Store users accounts in-app, ASP.NET Core hosted), I'm able to run the app, register and login, but when I try to retrieve the logged-in ApplicationUser on the Server through the UserManager I'm always getting null. My Startup ConfigureServices() looks like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddIdentityServer()
.AddApiAuthorization<ApplicationUser, ApplicationDbContext>();
services.AddAuthentication()
.AddIdentityServerJwt();
services.AddControllersWithViews();
services.AddRazorPages();
}
I'm trying to retrieve the ApplicationUser in a Controller like this:
var currentApplicationUser = await userManager.GetUserAsync(User).ConfigureAwait(false);
What resolved the issue for me was adding:
services.Configure<IdentityOptions>(options => options.ClaimsIdentity.UserIdClaimType = ClaimTypes.NameIdentifier);
Not sure if this behavior is expected or not, but might be needed to add this line of code as part of the template or fix the issue causing this.
Document Details
⚠ Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.
- ID: c9942b0a-a7fb-0d34-9201-af0963affa9e
- Version Independent ID: 19770710-5225-a1ea-e082-65da6ba4a49a
- Content: ASP.NET Core Blazor authentication and authorization
- Content Source: aspnetcore/security/blazor/index.md
- Product: aspnet-core
- Technology: aspnetcore-security
- GitHub Login: @guardrex
- Microsoft Alias: riande
Hello @x6060x ... Thanks for posting that. We were just discussing a similar scenario (with Identity Server) on #17402.
@javiercn Is it by-design that the dev would add ...
services.Configure<IdentityOptions>(options =>
options.ClaimsIdentity.UserIdClaimType = ClaimTypes.NameIdentifier);
... to their Server project (in which case we'll document it permanently), or should it only be documented temporarily while it's added to the hosted template? ... or is there another (better) solution?
btw @x6060x ... You've been awarded 🥇 Tip of the Day!:tm: 🥇 for that. It also solved the problem we were having for Identity Server server-side (getting username, email, phone, etc.) on #17402.
Whether or not it becomes part of the template or not, we'll still need it documented (at least temporarily). I have an open auth PR right now where I'm working on a bunch of little auth things. I'm going to add this today. We'll keep your issue here open for feedback from engineering on their plan.