0
votes

I'm using .Net Core for my API, so no views or whatsoever. I'm also using ASP.net Core Identity framework to authorize users in my database. For logging in users, I use this code:

private string GenerateAuthenticationResult(ApplicationUser user)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var key = Encoding.ASCII.GetBytes(_jwtSettings.Secret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                // Things to be included and encoded in the token
                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("id", user.Id)
                }),
                // Token will expire 2 hours from which it was created
                Expires = DateTime.UtcNow.AddHours(2),
                //
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };

            var token = tokenHandler.CreateToken(tokenDescriptor);

            return tokenHandler.WriteToken(token);
        }

This works like a charm for authenticating user actions, but how can I know whom my server is talking to provided that the user used the token I provided earlier for logging in in his request header (Bearer).

TL;dr

I want to extract user ID or user Email from the token provided in the request header.

Thanks.

1

1 Answers

1
votes

You can use AddJwtBearer validating JWT tokens :

var sharedKey = new SymmetricSecurityKey(
            Encoding.UTF8.GetBytes("yourkey"));
services.AddAuthentication(x =>
{
    x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
    x.RequireHttpsMetadata = false;
    x.SaveToken = true;

    x.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = sharedKey,

        ValidateIssuer = false,
        ValidateAudience = false,
        ValidateLifetime = false,            
    };
});

And enable asp.net core authentication middleware via adding app.UseAuthentication(); in Configure method . After that , you can add [Authorize] attribute on protected actions/controllers .

To get the email and user id after authentication in action :

var  email= User.Claims.Where(x => x.Type == ClaimTypes.Email).FirstOrDefault()?.Value;
var  userid= User.Claims.Where(x => x.Type == "id").FirstOrDefault()?.Value;

Here ClaimTypes.Email is used since JwtRegisteredClaimNames.Email will map to ClaimTypes.Email by middleware automatically . See source code .

Here are some useful articles for JWT Authentication :

https://jasonwatmore.com/post/2018/08/14/aspnet-core-21-jwt-authentication-tutorial-with-example-api

https://jasonwatmore.com/post/2019/10/11/aspnet-core-3-jwt-authentication-tutorial-with-example-api