5

I have some issues with my .NET CORE 2.1 web api. Im using Identity framework and JWT-tokens for authentication, but whenever I try to get the current user in a controller I get a null reference error.

All settings look fine from what I can see, and I've tried to manually set the key for Identity, but still getting the same error. Any ideas?

Controller:

        var user = await _userManager.GetUserAsync(User);

Startup.cs:

    public void ConfigureServices(IServiceCollection services)
    {
      services.AddIdentity<LoginUser, IdentityRole>(options => {
            options.ClaimsIdentity.UserIdClaimType = 
            ClaimTypes.NameIdentifier;
            })
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();
    }

Claims in token-generation:

        var claims = new List<Claim>
        {
            new Claim(JwtRegisteredClaimNames.Sub, user.Id),
            new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
            new Claim(JwtRegisteredClaimNames.Email, email),
            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
        };

1 Answers1

3

Can't really explain why this happens, I suppose that this happens because user is not really logged in since JWT is stateless.

But, I managed to get current user thanks to the following snippet :

private async Task<AppUser> GetUser()
        => await _userManager.FindByIdAsync(User.Claims.FirstOrDefault(c => string.Equals(c.Type, Constants.Strings.JwtClaimIdentifiers.Id, StringComparison.InvariantCultureIgnoreCase))?.Value);
Selmir
  • 1,136
  • 1
  • 11
  • 21
  • When trying that I get a Exception: Infinite recursion during resource lookup within System.Private.CoreLib. This may be a bug in System.Private.CoreLib, or potentially in certain extensibility points such as assembly resolve events or CultureInfo names. Resource name: Arg_NullReferenceException –  Aug 21 '18 at 09:01
  • Did you replaced `Constants.Strings.JwtClaimIdentifiers.Id` by `JwtRegisteredClaimNames.Sub` ? – Selmir Aug 21 '18 at 13:04