Skip to content

Instantly share code, notes, and snippets.

@vanillajonathan
Created September 27, 2018 13:35
Show Gist options
  • Save vanillajonathan/7666c4b567b75428ae5d36a03a408f13 to your computer and use it in GitHub Desktop.
Save vanillajonathan/7666c4b567b75428ae5d36a03a408f13 to your computer and use it in GitHub Desktop.
Generate a JWT token
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Principal;
using System.Text;
using Microsoft.IdentityModel.Tokens;
namespace Example
{
class Token
{
public string GenerateToken(IIdentity identity)
{
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["API:Key"]));
var tokenDescriptor = new SecurityTokenDescriptor
{
Audience = _configuration["API:Audience"],
Issuer = _configuration["API:Issuer"],
SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256),
Subject = new ClaimsIdentity(identity)
};
var handler = new JwtSecurityTokenHandler();
var token = handler.CreateJwtSecurityToken(tokenDescriptor);
var encoded = handler.WriteToken(token);
return encoded;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment