Skip to content

Instantly share code, notes, and snippets.

@wgross
Last active March 23, 2021 18:58
Show Gist options
  • Save wgross/b803b2f01cc87f59a02c08cfcc688c5a to your computer and use it in GitHub Desktop.
Save wgross/b803b2f01cc87f59a02c08cfcc688c5a to your computer and use it in GitHub Desktop.
Creates an asymmetric key, signs a JWT and validates the signature
// https://medium.com/dev-genius/jwt-authentication-in-asp-net-core-e67dca9ae3e8
var rsa = RSA.Create();
var keyPair = (
prv: rsa.ExportRSAPrivateKey(),
pub: rsa.ExportRSAPublicKey()
);
// create token and sign it with private key
var rsa_signer = RSA.Create();
rsa_signer.ImportRSAPrivateKey(source: keyPair.prv, bytesRead: out int _);
var signingCredentials = new SigningCredentials(
key: new RsaSecurityKey(rsa_signer),
algorithm: SecurityAlgorithms.RsaSha256 // Important to use RSA version of the SHA algo
);
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 rsa_validater = RSA.Create();
rsa_validater.ImportRSAPublicKey(source: keyPair.pub, bytesRead: out int _);
var principal = new JwtSecurityTokenHandler().ValidateToken(encodedSignedToken, new TokenValidationParameters
{
ValidateLifetime = true,
ValidateAudience = true,
ValidateIssuer = true,
ValidIssuer = "issuer",
ValidAudience = "audience",
IssuerSigningKey = new RsaSecurityKey(rsa_validater)
}, 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