Alper Alpdoğan
Alper Alpdoğan

Reputation: 142

JWT Token Accessing AuthenticatedUser

I'm trying to access the user Id from the token but everything I try returns null. The generated token has the necessary information so I don't think it's the token generation.

This is the part creates the token

        var tokenHandler = new JwtSecurityTokenHandler();
        var key = Encoding.ASCII.GetBytes(_jwtSettings.Secret);
        var tokenDescriptor = new SecurityTokenDescriptor()
        {
            Subject = new ClaimsIdentity(new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, user.Email),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(JwtRegisteredClaimNames.Email, user.Email),
                new Claim(ClaimTypes.NameIdentifier, existingAppUser.Id),
                new Claim("id", existingAppUser.Id),
            }),
            Expires = DateTime.UtcNow.AddDays(7),
            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
        };

        var token = tokenHandler.CreateToken(tokenDescriptor);

        return new AuthenticationResult()
        {
            Token = tokenHandler.WriteToken(token)
        };

When I decode the generated token I can see all of the claims in the token but I can't access it on the project.

This is the part trying to access the name identifier or the id claims

        var claimsList = _httpContextAccessor.HttpContext.User.Claims.ToList();

        var identityName = _httpContextAccessor.HttpContext.User.Identity.Name;

        var nameId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;

        var id = _httpContextAccessor.HttpContext.User.FindFirst(x => x.Type == "id")?.Value;

This is the JWT Configuration from Startup

services.AddAuthentication(x =>
        {
            x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
            x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
            .AddJwtBearer(x =>
            {
                x.SaveToken = true;
                x.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                {
                    ValidateIssuerSigningKey = false,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtSettings.Secret)),
                    ValidateAudience = false,
                    ValidateLifetime = true,
                    ValidateIssuer = false
                };
            });

        services.AddAuthorization();
        services.AddHttpContextAccessor();

This is the class I'm trying to access it from

    public class CurrentUserService : ICurrentUserService
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public CurrentUserService( IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    public string UserId { get => _httpContextAccessor.HttpContext.User.Claims.Single(x => x.Type == "id").Value; }

    public string GetUserId()
    {
        var claimsList = _httpContextAccessor.HttpContext.User.Claims.ToList();

        var identityName = _httpContextAccessor.HttpContext.User.Identity.Name;

        var nameId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;

        var id = _httpContextAccessor.HttpContext.User.FindFirst(x => x.Type == "id")?.Value;

        return "123";
    }
}

I don't know what I am missing here. How do I get the userId from the token?

Upvotes: 8

Views: 380

Answers (1)

Alper Alpdoğan
Alper Alpdoğan

Reputation: 142

Well It turns out I forgot to put

    [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]

in the necessary controllers.

Upvotes: 6

Related Questions