0

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

2 Answers 2

1

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?

Sign up to request clarification or add additional context in comments.

3 Comments

The user is authenticated I can see the token in the session tab of chrome, User is null, So if I do User. Identity throws a null pointer exception
Clarified my answer
httpcontext.request is null in my case
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.