jwt bearer token c# code example

Example 1: 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);    
}

Example 2: asp net core identity bearer token authentication example

[HttpPost]
public async Task<IActionResult> AccessToken([FromForm]string code, [FromForm]string grant_type, [FromForm]string redirect_uri, [FromForm]string client_id, [FromForm]string client_secret)
{
    // Check if code is correct and if client credentials are correct.
    if (grant_type != "authorization_code")
    {
        return Redirect(redirect_uri + "?error=unsupported_response_type");
    }
    
    if (!clientValidator.Valid(client_id, client_secret))
    {
        return Redirect(redirect_uri + "?error=access_denied");
    }
    
    // Extract the URI and user
    string previous_uri = codeAndURIStorage.Load(code);
    string user = codeAndUserStorage.Load(code);
    codeAndURIStorage.Delete(code);
    codeAndUserStorage.Delete(code);

    // Check if the new uir is the same as the previous and that the userId was found
    if (redirect_uri != previous_uri)
    {
        return BadRequest("'redirect_uri' was inconsistent.");
    }
    
    if (user == null)
    {
        return BadRequest("Couldn't find user associated with the given code.");
    }

    // Creates the signed JWT
    var symmetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["TokenOptions:Key"]))
    var tokenHandler = new JwtSecurityTokenHandler();
    var tokenDescriptor = new SecurityTokenDescriptor
    {
        Subject = new ClaimsIdentity(new Claim[]
        {
            new Claim(ClaimTypes.Name, user)
        }),
        Expires = DateTime.UtcNow.AddYears(2),
        Issuer = "MyWebsite.com",
        Audience = "MyWebsite.com",
        SigningCredentials = new SigningCredentials(symmetricSecurityKey, SecurityAlgorithms.HmacSha256Signature)
    };
    var token = tokenHandler.CreateToken(tokenDescriptor);
    var access_token = tokenHandler.WriteToken(token);

    // Returns the 'access_token' and the type in lower case
    return Ok(new { access_token, token_type="bearer" });
}