Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 929
Alper Alpdoğan Avatar asked Nov 27 '20 08:11

Alper Alpdoğan


People also ask

Can JWT be used as access token?

JWTs can be used as OAuth 2.0 Bearer Tokens to encode all relevant parts of an access token into the access token itself instead of having to store them in a database.

What if someone gets my JWT token?

One of the most important steps is to ask your clients to change their passwords immediately if there's an instance where the JWT token is stolen. Changing the password of an account will prevent attackers from exploiting the account and would eventually help in avoiding a data breach.

How do I authenticate JWT tokens?

To authenticate a user, a client application must send a JSON Web Token (JWT) in the authorization header of the HTTP request to your backend API. API Gateway validates the token on behalf of your API, so you don't have to add any code in your API to process the authentication.


Video Answer


1 Answers

Well It turns out I forgot to put

    [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]

in the necessary controllers.

like image 54
Alper Alpdoğan Avatar answered Nov 02 '22 05:11

Alper Alpdoğan