Created
September 27, 2018 13:35
-
-
Save vanillajonathan/7666c4b567b75428ae5d36a03a408f13 to your computer and use it in GitHub Desktop.
Generate a JWT token
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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