简体   繁体   中英

User is null with Asp.net core 3 + visual studio template + Identity server (ApiAuthorization.IdentityServer, AspNetCore.Identity.UI)

I am trying to get the current login user in the base controller

public abstract class BaseController : ControllerBase
    {
        private readonly UserManager<ApplicationUser> _userManager;
        public BaseController()
        {
            var user =  _userManager.FindByNameAsync(User.Identity.Name).Result;
            
        }
    }

However, the user is null, so User.Identity.Name is created null pointer exception.

I am using the Asp.net core 3.1 with Angular template from visual studio and Identity server as

<PackageReference Include="Microsoft.AspNetCore.ApiAuthorization.IdentityServer" Version="3.1.8" />
 <PackageReference Include="Microsoft.AspNetCore.Identity.UI" Version="3.1.8" />

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");
                }
            });

Profile.service

public async Task GetProfileDataAsync(ProfileDataRequestContext context)
        {
            var user = await _userManager.GetUserAsync(context.Subject);
            var claims = new List<Claim>
            {
                new Claim("FullName", $"{user.FirstName} {user.LastName}" ),
                new Claim("Email", user.Email ),
                new Claim("UserId", user.Id),
                new Claim("name", user.Email),
            };
            context.IssuedClaims.AddRange(claims);
        }

You need to first check if user.Identity is not null. It will be null for unauthenticated users.

You should program with defense in mind, because you might get requests to any endpoint without nor or invalid session cookies. So you should program and protect about that usecase.

If the user is null, you could also challenge the user and redirect it to your IdentityServer.

You could for example check in the httpcontext.request object and see if the request that triggers the null exception contains any cookies at all?

HttpContext is called in the constructor and then there isnt a HttpContext instantiated yet since that happens when a client connects to this controller. So moving the code to the method, works

 public abstract class BaseController : ControllerBase
    {
        private readonly UserManager<ApplicationUser> _userManager;
        public BaseController(UserManager<ApplicationUser> userManager)
        {
            _userManager = userManager;
        }
        
        protected async Task<(string , string, string)> GetUser()
        {
            var email = User.Identity.Name; 
            var user = await _userManager.FindByEmailAsync(email);
            return (user.Id , $"{user.FirstName} {user.LastName}", user.Email);
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM