Skip to content

Instantly share code, notes, and snippets.

@NMillard
Last active August 4, 2022 09:17
Show Gist options
  • Select an option

  • Save NMillard/098ae70f4b3b8945d245a839e7f096e8 to your computer and use it in GitHub Desktop.

Select an option

Save NMillard/098ae70f4b3b8945d245a839e7f096e8 to your computer and use it in GitHub Desktop.
Endpoints to create and verify asymmetric JWT
// ... imports
namespace Authentication.WebClient.Controllers {
[ApiController]
[Route("api/[controller]/[action]")]
public class AuthorizationController : ControllerBase {
private readonly IConfiguration configuration;
public AuthorizationController(IConfiguration configuration) {
this.configuration = configuration; // Needed to access the stored JWT secret key
}
[HttpPost]
public IActionResult GenerateTokenAsymmetric() {
using RSA rsa = RSA.Create();
rsa.ImportRSAPrivateKey( // Convert the loaded key from base64 to bytes.
source: Convert.FromBase64String(configuration["Jwt:Asymmetric:PrivateKey"]), // Use the private key to sign tokens
bytesRead: out int _); // Discard the out variable
var signingCredentials = new SigningCredentials(
key: new RsaSecurityKey(rsa),
algorithm: SecurityAlgorithms.RsaSha256 // Important to use RSA version of the SHA algo
);
DateTime jwtDate = DateTime.Now;
var jwt = new JwtSecurityToken(
audience: "jwt-test",
issuer: "jwt-test",
claims: new Claim[] {new Claim(ClaimTypes.NameIdentifier, "some-username")},
notBefore: jwtDate,
expires: jwtDate.AddSeconds(10),
signingCredentials: signingCredentials
);
string token = new JwtSecurityTokenHandler().WriteToken(jwt);
return Ok(new {
jwt = token,
unixTimeExpiresAt = new DateTimeOffset(jwtDate).ToUnixTimeMilliseconds(),
});
}
[HttpGet]
[Authorize(AuthenticationSchemes = "Asymmetric")] // Use the "Asymmetric" authentication scheme
public IActionResult ValidateTokenAsymmetric() {
return Ok();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment