Menu

Asp.net core API – Issue Jwt token upon successful login

This is a continuation of my previous post of Setting up Asp.net core API for JwtBearer Authentication. Below we will discuss how to issue Jwt token upon successful login.

You can use the method below to issue tokens upon successful login.

public string CreateToken(int userId, string email, string firstName, string lastName, string role, int organisationId)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var key = Encoding.ASCII.GetBytes("your app Secret");
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new [] {
                    new Claim(ClaimTypes.Name, email),
                    new Claim("UserId", userId.ToString()),
                    new Claim("FirstName", firstName),
                    new Claim("LastName", lastName),
                    .....................
                    .....................
                    new Claim(ClaimTypes.Role, role)
                }),
                Expires = DateTime.UtcNow.AddHours(3), // how long you want to make it valid
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);

            return tokenString;
        }

That is pretty much it. If you guys see any issues please let me know

 

 

Leave a comment