KestrunHostAuthExtensions.AddJwtBearerAuthentication method
Adds JWT Bearer authentication to the Kestrun host.
Use this for APIs that require token-based authentication.
public static KestrunHost AddJwtBearerAuthentication(this KestrunHost host, string scheme,
TokenValidationParameters validationParameters, Action<JwtBearerOptions>? configureJwt = null,
ClaimPolicyConfig? claimPolicy = null)
parameter | description |
---|---|
host | The Kestrun host instance. |
scheme | The authentication scheme name (e.g. “Bearer”). |
validationParameters | Parameters used to validate JWT tokens. |
configureJwt | Optional hook to customize JwtBearerOptions. |
claimPolicy | Optional authorization policy configuration. |
Examples
HS512 (HMAC-SHA-512, symmetric)
RS256 (RSA-SHA-256, asymmetric)
Requires a PEM-encoded private key file.
using var rsa = RSA.Create();
rsa.ImportFromPem(File.ReadAllText("private-key.pem"));
var rsaKey = new RsaSecurityKey(rsa);
host.AddJwtBearerAuthentication(
scheme: "Rs256",
issuer: "KestrunApi",
audience: "KestrunClients",
validationKey: rsaKey,
validAlgorithms: new[] { SecurityAlgorithms.RsaSha256 });
ES256 (ECDSA-SHA-256, asymmetric)
Requires a PEM-encoded private key file.
using var ecdsa = ECDsa.Create(ECCurve.NamedCurves.nistP256);
var esKey = new ECDsaSecurityKey(ecdsa);
host.AddJwtBearerAuthentication(
"Es256", "KestrunApi", "KestrunClients",
esKey, new[] { SecurityAlgorithms.EcdsaSha256 });
See Also
- class KestrunHost
- class ClaimPolicyConfig
- class KestrunHostAuthExtensions
- namespace Kestrun.Hosting