User.Identity.IsAuthenticated always false and User.Identity.Claims is null in .NET Core JWT Auth

34 Views Asked by At

Program.cs:

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            //ValidateIssuer = true,
            //ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
        };
    });

GenTokenController -- returns a proper token with the correct values

private string GenerateJwtToken(CurrentUserVM currentUser)
{
    var tokenHandler = new JwtSecurityTokenHandler();
    var key = Encoding.ASCII.GetBytes(_config.GetSection("Jwt:Key").Value);
    var ExpireMinutes = _config.GetSection("Jwt:ExpireMinutes").Value;
    var tokenDescriptor = new SecurityTokenDescriptor
    {
        Subject = new ClaimsIdentity(new Claim[]
        {
               new Claim(ClaimTypes.NameIdentifier, currentUser.UserId.ToString()),
               new Claim(ClaimTypes.GroupSid, currentUser.OrgId.ToString()),
               new Claim(ClaimTypes.Role, currentUser.RoleCode)
        }),
        Expires = DateTime.UtcNow.AddMinutes(Convert.ToInt32(ExpireMinutes)),
        SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key),
                                                                   SecurityAlgorithms.HmacSha512Signature)
    };
    var token = tokenHandler.CreateToken(tokenDescriptor);
    return tokenHandler.WriteToken(token);
}

UserController -- trying to get current user:

[HttpGet]
[Authorize(Roles ="Admin")]
public async Task<IActionResult> GetUsers()
{
     var curr_user = GetCurrentUser();
     var users = new List<User>();
     return Ok(users);
}

private CurrentUserVM GetCurrentUser()
{
    if (HttpContext == null || HttpContext.User == null)
    {
        return null;
    }

    var identity = HttpContext.User.Identity as ClaimsIdentity;

    if (identity != null)
    {
        var userClaims = identity.Claims;

        if (userClaims == null || !userClaims.Any())
        {
            return null;
        }

        return new CurrentUserVM
        {
            OrgId = int.Parse(userClaims.FirstOrDefault(x => x.Type == ClaimTypes.GroupSid)?.Value),
            UserId = int.Parse(userClaims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier)?.Value),
            RoleCode = userClaims.FirstOrDefault(x => x.Type == ClaimTypes.Role)?.Value
        };
    }
    return null;
}

When [Authorize] attribute is used, this call returns 401, but not used in GetCurrentUser() function

var userClaims = identity.Claims;

returns null and User.Identity.IsAuthenticated is always false.

I tried adding

builder.Services.AddHttpContextAccessor(); 

and then use a serviceProvider - but that did not work either.

1

There are 1 best solutions below

1
Qing Guo On

If you don't want to validate the server (ValidateIssuer = true) that generates the token and validate the recipient of the token is authorized to receive (ValidateAudience = true), try to set it false not comment it.

ValidateIssuer = false,
ValidateAudience = false,