Search code examples
c#asp.netasp.net-coreasp.net-identityvisual-studio-templates

User.Identity null pointer exception with SPA(Angular) visual studio angular template


I am using the visual studio angular template, to create the project, trying to access the user claims User.Identity.Name. Since the user is null, so getting an null pointer exception.

I have followed the instruction from here https://learn.microsoft.com/en-us/aspnet/core/security/authentication/identity-api-authorization?view=aspnetcore-3.1

which uses the AddApiAuthorization, AddIdentityServerJwt, OidcConfigurationController

Startup.cs

services.AddIdentityServer()
                .AddApiAuthorization<ApplicationUser, ApplicationDbContext>()
                .AddProfileService<ProfileService>();
            
            services.AddAuthentication()
                .AddIdentityServerJwt();

 app.UseAuthentication();
            app.UseIdentityServer();
            app.UseAuthorization();

 app.UseSpa(spa =>
            {
                spa.Options.SourcePath = "ClientApp";
                if (env.IsDevelopment())
                {
                    spa.UseAngularCliServer(npmScript: "start");
                }
            });

In the base controller I am trying to access the user claim

    [Authorize]
    public abstract class BaseController : ControllerBase
        {
           
            private readonly UserManager<ApplicationUser> _userManager;
            public BaseController()
            {
var identity = HttpContext.User.Identity as ClaimsIdentity;
                var user =  _userManager.FindByNameAsync(User.Identity.Name).Result;
                
            }
        }

The User is null, after login successful from the identity server. The basecontroller is decorated with [Authorize] The break point is working after the authorization

enter image description here


Solution

  • It's not the User that is null, it's HttpContext that is null.

    HttpContext is called in the constructor and then there isnt a HttpContext instantiated yet since that happens when a client connects to this controller. Move your code inside a method within the controller and you'll find that HttpContext is set.