Upgrade to 4.0Changelog
Reference

JWT module

JWT access tokens with a hashed refresh token, cookie or JSON body transport, and reuse detection.

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):

MethodPathNotes
POST/createLogin; rate-limited. Returns { "accessToken", "tokenType": "Bearer" }. Body transport also returns refreshToken
POST/refreshCookie: refresh cookie + CSRF. Body: { "refreshToken" }, no CSRF. Rate-limited either way
GET/verify[Authorize] JWT Bearer → 204. Does not return a refresh token
POST/logoutCookie: CSRF. Body: { "refreshToken" }. Revokes the refresh family on the server
GET/csrfTokenCookie 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:

  • email
  • password
  • twoFactorCode (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.

ResultResponse
Success200 { "accessToken", "tokenType": "Bearer" } (SimpleJwtTokenResponse). Cookie transport also sets the refresh cookie. Body transport adds refreshToken and sets no refresh cookie
email or password missing400 { "error": "invalid_request", "error_description" }. This body is not problem details.
Wrong credentials, lockout, or unconfirmed account401 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.

Used when RefreshTokenTransport is Cookie (the default).

PropertyValue
NameAuthEndpoints.Jwt.RefreshToken
FlagsHttpOnly, SameSite=Strict, Secure when HTTPS, Path=/
LifetimeUntil the family's absolute end. Default 14 days from sign-in, not extended by refresh

Options

PropertyDefaultNotes
IssuerJwtRejected in Production
AudienceJwtAudienceRejected in Production
AccessTokenLifetime15 minutesOn SimpleJwtOptions
RefreshTokenTransportCookieOn 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
RefreshTokenLifetime14 daysOn JwtSessionOptions. Per-token window. Cannot pass AbsoluteLifetime
AbsoluteLifetime14 daysOn JwtSessionOptions. Family cap from the original sign-in
SigningOptionsSymmetricSee Signing for Symmetric, RSA, ECDSA, and X509
TokenValidationParametersnullSee Advanced — custom ASP.NET Core JWT Bearer validation

Signing

Configure SimpleJwtOptions.SigningOptions (SimpleJwtSigningOptions). Default algorithm is Symmetric (HS256).

AlgorithmRequired propertyDefault JWT algNotes
Symmetric (default)SymmetricKeyHS256≥ 32 UTF-8 bytes
RsaRsaKeyRS256Or use X509 for cert-backed RSA
EcdsaEcdsaKeyES256
X509CertificateRS256Certificate 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*: SymmetricKey is required and must be at least 256 bits (32 UTF-8 bytes)
  • Rsa: RsaKey is required. A host that sets Rsa and supplies only Certificate fails at startup with RsaKey is required when Algorithm is Rsa. Set SimpleJwtOptions.SigningOptions.RsaKey.
  • X509: Certificate is required. A host that sets X509 and supplies only RsaKey fails at startup with Certificate is required when Algorithm is X509. Set SimpleJwtOptions.SigningOptions.Certificate.
  • Ecdsa / ES*: EcdsaKey is required
  • PS*: RsaKey is 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:

AlgorithmIssuerSigningKey type
SymmetricSymmetricSecurityKey
RsaRsaSecurityKey
EcdsaECDsaSecurityKey
X509X509SecurityKey

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

  1. Store/send access token as Authorization: Bearer ….
  2. Cookie transport: refresh and logout send the refresh cookie plus RequestVerificationToken from GET /auth/csrfToken. One refresh at a time.
  3. Body transport: keep refreshToken in memory or secure storage, and send it as JSON to POST /refresh and POST /logout. Do not send the refresh cookie. There is no csrfToken route.

Gotchas

  • Passkey register and login do not mint a Simple JWT unless you pass AuthEndpointsSession.Jwt to MapPasskeySignInEndpoints. See Passkeys. Do not send users through password /create after a successful passkey.
  • Migrate after UseRefreshToken(). Upgrading to the absolute lifetime adds AbsoluteExpiresAt. Backfill it from ExpiresAt. Recreate the table when upgrading from plaintext storage.
  • Call UseRateLimiter(). Call UseAntiforgery() for cookie transport.
  • IdentityBearer refresh tokens are not this store. They have no reuse detection.