JWT module
JWT sign-in: short-lived access tokens plus a hashed refresh token. The default transport is an HttpOnly refresh cookie. Set JwtSessionOptions.RefreshTokenTransport to Body when the client has no cookie jar. Pair with Identity management for register/manage.
DI
builder.Services.AddJwtEndpoints<AppUser, AppDbContext>(o =>
{
o.Issuer = "https://example.com";
o.Audience = "https://example.com";
o.SigningOptions.SymmetricKey = builder.Configuration["Jwt:SymmetricKey"];
o.RefreshTokenTransport = RefreshTokenTransport.Cookie; // default
// o.RefreshTokenTransport = RefreshTokenTransport.Body;
});
// Runs after AddJwtEndpoints. Set RefreshTokenTransport here to replace a copied Body value.
builder.Services.Configure<JwtSessionOptions>(session =>
{
session.RefreshTokenLifetime = TimeSpan.FromDays(14);
});
AddJwtEndpoints copies SimpleJwtOptions.RefreshTokenTransport onto JwtSessionOptions only when that value is not Cookie. The default Cookie leaves an earlier Configure<JwtSessionOptions> in place. An unknown transport value fails when AddJwtEndpoints runs. A Configure<JwtSessionOptions> registered after AddJwtEndpoints replaces the copy.
AddJwtEndpoints returns a SimpleJwtBuilder for replacing services:
AddAccessTokenGenerator<T>AddRefreshTokenService<T>AddErrorDescriber<T>
EF mapping
using AuthEndpoints.Jwt;
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.UseRefreshToken(); // schema AuthEndpoints, table AuthEndpointsRefreshTokens
}
Refresh tokens are stored as hashes only. Reuse of a rotated token revokes the whole family. The family ends at AbsoluteExpiresAt, which rotation does not extend. Logout revokes the family on the server. A security-stamp change does too.
Map
app.MapGroup("/auth").MapJwtAuthEndpoints<AppUser>();
MapJwtAuthEndpoints is MapJwtPasswordEndpoints (POST /create) plus MapJwtSessionEndpoints (POST /refresh, GET /verify, POST /logout, GET /csrfToken). Map them on different prefixes when create and the session should not share a path:
app.MapGroup("/auth").MapJwtPasswordEndpoints<AppUser>();
app.MapGroup("/session").MapJwtSessionEndpoints<AppUser>();
Each map throws InvalidOperationException when AddJwtEndpoints was not called. The message names AddJwtEndpoints. Cookie transport requires antiforgery on refresh and logout. AddJwtEndpoints does not register antiforgery. Call AddAntiforgery() before mapping that transport. Body transport does not map GET /csrfToken and does not require antiforgery. The choice is read from JwtSessionOptions when the session routes are mapped. AddJwtEndpoints copies a non-default SimpleJwtOptions.RefreshTokenTransport onto that options object.
Routes
Relative to the group prefix. The password facade uses Path (default /auth):
| Method | Path | Notes |
|---|---|---|
POST | /create | Login; rate-limited. Returns { "accessToken", "tokenType": "Bearer" }. Body transport also returns refreshToken |
POST | /refresh | Cookie: refresh cookie + CSRF. Body: { "refreshToken" }, no CSRF. Rate-limited either way |
GET | /verify | [Authorize] JWT Bearer → 204. Does not return a refresh token |
POST | /logout | Cookie: CSRF. Body: { "refreshToken" }. Revokes the refresh family on the server |
GET | /csrfToken | Cookie transport only |
POST /login, POST /emailCode/verify, and POST /create do not use antiforgery. Those routes accept JSON only, so a cross-site form cannot post the credentials: the browser sends a CORS preflight first. That login-CSRF limit matters only in cookie transport, where the response would store AuthEndpoints.Jwt.RefreshToken. Body transport does not set that cookie.
Create request body
SimpleJwtLoginRequest on POST /create:
emailpasswordtwoFactorCode(optional)twoFactorRecoveryCode(optional)
DefaultAuthenticator looks up email as an email first, then as a user name. It checks the password with lockout on failure, and it refuses an unconfirmed account when RequireConfirmedAccount is true.
| Result | Response |
|---|---|
| Success | 200 { "accessToken", "tokenType": "Bearer" } (SimpleJwtTokenResponse). Cookie transport also sets the refresh cookie. Body transport adds refreshToken and sets no refresh cookie |
email or password missing | 400 { "error": "invalid_request", "error_description" }. This body is not problem details. |
| Wrong credentials, lockout, or unconfirmed account | 401 problem details, detail Invalid credentials. |
Two-factor
MapJwtPasswordEndpoints and MapJwtAuthEndpoints run POST /create through the shared password pipeline. DefaultAuthenticator looks the user up and checks the password. An unknown email runs a password-hash verify, so it takes about as long as a wrong password.
When 2FA is enabled and neither code is provided, POST /create returns 401 with title RequiresTwoFactor, detail Two-factor authentication is required., and extension requiresTwoFactor: true. Retry the same request with twoFactorCode or twoFactorRecoveryCode.
A wrong authenticator code or recovery code calls AccessFailedAsync, returns 401 with detail Invalid credentials., and counts toward lockout. A replaced IAuthenticator<TUser> runs. JWT sign-in never sets the Identity two-factor remember-client cookie.
On MapJwtPasswordEndpoints and MapJwtAuthEndpoints, match failures on status and title. Those maps do not return Recovery code redemption failed.
Refresh response
Cookie transport: POST /refresh rotates the refresh cookie and returns 200 { "accessToken" }, with no tokenType and no refreshToken. Body transport returns 200 { "accessToken", "tokenType": "Bearer", "refreshToken" } and sets no refresh cookie. A missing or invalid refresh token returns 400 { "errors": ["..."] }. In body mode, a request whose content type is not JSON returns 415. Reuse of a rotated refresh token revokes the whole family, so the previous successor stops working too. Callers have to serialize refresh.
The family's absolute end is fixed at sign-in. The default is 14 days (JwtSessionOptions.AbsoluteLifetime). A later refresh cannot move it later.
Refresh cookie
Used when RefreshTokenTransport is Cookie (the default).
| Property | Value |
|---|---|
| Name | AuthEndpoints.Jwt.RefreshToken |
| Flags | HttpOnly, SameSite=Strict, Secure when HTTPS, Path=/ |
| Lifetime | Until the family's absolute end. Default 14 days from sign-in, not extended by refresh |
Options
| Property | Default | Notes |
|---|---|---|
Issuer | Jwt | Rejected in Production |
Audience | JwtAudience | Rejected in Production |
AccessTokenLifetime | 15 minutes | On SimpleJwtOptions |
RefreshTokenTransport | Cookie | On SimpleJwtOptions and JwtSessionOptions. AddJwtEndpoints copies a non-default SimpleJwtOptions value. Body returns refreshToken and skips antiforgery. An earlier Configure<JwtSessionOptions> stays when the value is left at Cookie. A later configure replaces it |
RefreshTokenLifetime | 14 days | On JwtSessionOptions. Per-token window. Cannot pass AbsoluteLifetime |
AbsoluteLifetime | 14 days | On JwtSessionOptions. Family cap from the original sign-in |
SigningOptions | Symmetric | See Signing for Symmetric, RSA, ECDSA, and X509 |
TokenValidationParameters | null | See Advanced — custom ASP.NET Core JWT Bearer validation |
Signing
Configure SimpleJwtOptions.SigningOptions (SimpleJwtSigningOptions). Default algorithm is Symmetric (HS256).
Algorithm | Required property | Default JWT alg | Notes |
|---|---|---|---|
Symmetric (default) | SymmetricKey | HS256 | ≥ 32 UTF-8 bytes |
Rsa | RsaKey | RS256 | Or use X509 for cert-backed RSA |
Ecdsa | EcdsaKey | ES256 | |
X509 | Certificate | RS256 | Certificate must include a private key |
Use AlgorithmOverride to pick a different JWT algorithm string (for example SecurityAlgorithms.RsaSha512, EcdsaSha384, or HmacSha512). Startup validation requires the property ToSecurityKey() reads for Algorithm. An override whose name starts with HS, ES, or PS also requires that prefix's key.
The same SigningOptions shape works on the password facade via o.Jwt = jwt => { … } or on compose via AddJwtEndpoints as shown below.
Symmetric
builder.Services.AddJwtEndpoints<AppUser, AppDbContext>(o =>
{
o.Issuer = "https://example.com";
o.Audience = "https://example.com";
o.SigningOptions.Algorithm = SimpleJwtSigningOptions.SigningAlgorithm.Symmetric; // default
o.SigningOptions.SymmetricKey = builder.Configuration["Jwt:SymmetricKey"];
});
RSA
using System.Security.Cryptography;
var rsa = RSA.Create();
rsa.ImportFromPem(File.ReadAllText("keys/rsa-private.pem"));
builder.Services.AddJwtEndpoints<AppUser, AppDbContext>(o =>
{
o.Issuer = "https://example.com";
o.Audience = "https://example.com";
o.SigningOptions.Algorithm = SimpleJwtSigningOptions.SigningAlgorithm.Rsa;
o.SigningOptions.RsaKey = rsa;
});
ECDSA
using System.Security.Cryptography;
var ecdsa = ECDsa.Create();
ecdsa.ImportFromPem(File.ReadAllText("keys/ecdsa-private.pem"));
builder.Services.AddJwtEndpoints<AppUser, AppDbContext>(o =>
{
o.Issuer = "https://example.com";
o.Audience = "https://example.com";
o.SigningOptions.Algorithm = SimpleJwtSigningOptions.SigningAlgorithm.Ecdsa;
o.SigningOptions.EcdsaKey = ecdsa;
});
X509
using System.Security.Cryptography.X509Certificates;
var certificate = X509CertificateLoader.LoadPkcs12FromFile(
"certs/signing.pfx",
builder.Configuration["Jwt:CertificatePassword"]);
builder.Services.AddJwtEndpoints<AppUser, AppDbContext>(o =>
{
o.Issuer = "https://example.com";
o.Audience = "https://example.com";
o.SigningOptions.Algorithm = SimpleJwtSigningOptions.SigningAlgorithm.X509;
o.SigningOptions.Certificate = certificate;
});
PEM with private key is also fine when you build an X509Certificate2 that includes the key (for example X509Certificate2.CreateFromPemFile).
AlgorithmOverride
using Microsoft.IdentityModel.Tokens;
builder.Services.AddJwtEndpoints<AppUser, AppDbContext>(o =>
{
o.Issuer = "https://example.com";
o.Audience = "https://example.com";
o.SigningOptions.Algorithm = SimpleJwtSigningOptions.SigningAlgorithm.Rsa;
o.SigningOptions.RsaKey = rsa;
o.SigningOptions.AlgorithmOverride = SecurityAlgorithms.RsaSha512;
});
Validation notes
- Symmetric /
HS*:SymmetricKeyis required and must be at least 256 bits (32 UTF-8 bytes) Rsa:RsaKeyis required. A host that setsRsaand supplies onlyCertificatefails at startup withRsaKey is required when Algorithm is Rsa. Set SimpleJwtOptions.SigningOptions.RsaKey.X509:Certificateis required. A host that setsX509and supplies onlyRsaKeyfails at startup withCertificate is required when Algorithm is X509. Set SimpleJwtOptions.SigningOptions.Certificate.Ecdsa/ES*:EcdsaKeyis requiredPS*:RsaKeyis required- Production still rejects the default issuer and audience. See Prepare for production.
Advanced
TokenValidationParameters
Access-token validation always goes through ASP.NET Core JWT Bearer and TokenValidationParameters. Changing the signing algorithm does not bypass that path — it only changes which SecurityKey is used.
When SimpleJwtOptions.TokenValidationParameters is null (the default), AddJwtEndpoints builds parameters like this and assigns them to JwtBearerOptions.TokenValidationParameters:
new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = options.Issuer,
ValidateAudience = true,
ValidAudience = options.Audience,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = options.SigningOptions.ToSecurityKey()
}
ToSecurityKey() returns the key type for the configured algorithm:
| Algorithm | IssuerSigningKey type |
|---|---|
| Symmetric | SymmetricSecurityKey |
| Rsa | RsaSecurityKey |
| Ecdsa | ECDsaSecurityKey |
| X509 | X509SecurityKey |
Signing (token creation) uses SigningOptions.ToSigningCredentials() (HS256 / RS256 / ES256 / etc.). Validation checks the JWT signature against IssuerSigningKey.
Custom TokenValidationParameters
If you set TokenValidationParameters yourself, that object is used as-is. AuthEndpoints does not merge SigningOptions into it — you must set IssuerSigningKey (and issuer/audience rules) on your override:
using Microsoft.IdentityModel.Tokens;
builder.Services.AddJwtEndpoints<AppUser, AppDbContext>(o =>
{
o.Issuer = "https://example.com";
o.Audience = "https://example.com";
o.SigningOptions.Algorithm = SimpleJwtSigningOptions.SigningAlgorithm.Rsa;
o.SigningOptions.RsaKey = rsa;
// Used for token creation (SigningOptions) AND you must wire validation yourself:
o.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = "https://example.com",
ValidateAudience = true,
ValidAudience = "https://example.com",
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = o.SigningOptions.ToSecurityKey()
};
});
JwtBearerOptions callback
AddJwtEndpoints also accepts an optional Action<JwtBearerOptions> to tweak the bearer handler after TokenValidationParameters are assigned (events, metadata address, etc.):
builder.Services.AddJwtEndpoints<AppUser, AppDbContext>(
o =>
{
o.Issuer = "https://example.com";
o.Audience = "https://example.com";
o.SigningOptions.SymmetricKey = builder.Configuration["Jwt:SymmetricKey"];
},
jwt =>
{
jwt.MapInboundClaims = false;
});
Client notes
- Store/send access token as
Authorization: Bearer …. - Cookie transport: refresh and logout send the refresh cookie plus
RequestVerificationTokenfromGET /auth/csrfToken. One refresh at a time. - Body transport: keep
refreshTokenin memory or secure storage, and send it as JSON toPOST /refreshandPOST /logout. Do not send the refresh cookie. There is nocsrfTokenroute.
Gotchas
- Passkey register and login do not mint a Simple JWT unless you pass
AuthEndpointsSession.JwttoMapPasskeySignInEndpoints. See Passkeys. Do not send users through password/createafter a successful passkey. - Migrate after
UseRefreshToken(). Upgrading to the absolute lifetime addsAbsoluteExpiresAt. Backfill it fromExpiresAt. Recreate the table when upgrading from plaintext storage. - Call
UseRateLimiter(). CallUseAntiforgery()for cookie transport. IdentityBearerrefresh tokens are not this store. They have no reuse detection.