Skip to content

Instantly share code, notes, and snippets.

@wgross
Last active March 14, 2021 12:04
Show Gist options
  • Save wgross/89ff4687438a5bd297d8517a103cb02e to your computer and use it in GitHub Desktop.
Save wgross/89ff4687438a5bd297d8517a103cb02e to your computer and use it in GitHub Desktop.
Creates a symmetric key, signs a JWT and validates the signature
// https://weblog.west-wind.com/posts/2021/Mar/09/Role-based-JWT-Tokens-in-ASPNET-Core
// create token and sign it with key
var signingCredentials = new SigningCredentials(
key: new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Thats a sufficiently long key")),
algorithm: SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer:"issuer",
audience: "audience",
claims: new List<Claim>
{
new Claim("username", "username")
},
notBefore: DateTime.UtcNow,
expires: DateTime.UtcNow.AddDays(1),
signingCredentials:signingCredentials);
var encodedSignedToken = new JwtSecurityTokenHandler().WriteToken(token).Dump("Encoded signed token");
// validate the token
var principal = new JwtSecurityTokenHandler().ValidateToken(encodedSignedToken, new TokenValidationParameters
{
ValidateLifetime = true,
ValidateAudience = true,
ValidateIssuer = true,
ValidIssuer = "issuer",
ValidAudience = "audience",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Thats a sufficiently long key"))
}, out var validatedToken);
principal.Dump("Validated principal");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment