step by step jwt authetication dotnet core api code example

Example 1: c# core jwt

// more generic
private string GenerateJSONWebToken()
{
    var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("MynameisJamesBond007"));
    var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
 
    var token = new JwtSecurityToken(
        issuer: "https://www.yogihosting.com",
        audience: "https://www.yogihosting.com",
        expires: DateTime.Now.AddHours(3),
        signingCredentials: credentials
        );
 
    return new JwtSecurityTokenHandler().WriteToken(token);
}

Example 2: c# asp.net mvc core implementing jwt

// .net token
private string GenerateJSONWebToken(UserModel userInfo)    
{    
    var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));    
    var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);    
    
    var claims = new[] {    
        new Claim(JwtRegisteredClaimNames.Sub, userInfo.Username),    
        new Claim(JwtRegisteredClaimNames.Email, userInfo.EmailAddress),    
        new Claim("DateOfJoing", userInfo.DateOfJoing.ToString("yyyy-MM-dd")),    
        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())    
    };    
    
    var token = new JwtSecurityToken(_config["Jwt:Issuer"],    
        _config["Jwt:Issuer"],    
        claims,    
        expires: DateTime.Now.AddMinutes(120),    
        signingCredentials: credentials);    
    
    return new JwtSecurityTokenHandler().WriteToken(token);    
}