Skip to content

You're viewing documentation for a pre-release version. View the latest stable version

Framework

JWT

JWT provides integrations between JWTKit and Vapor to make it easy to work with JWTs in your Vapor application.

Overview

For more details, see the Vapor Docs.

Verifying identity tokens

Identity tokens must be verified against the audience identifiers accepted by the application (client IDs for Apple, Google, and Microsoft; project IDs for Firebase). Provider helpers accept applicationIdentifier, or use the identifier configured on app.jwt.apple, app.jwt.google, app.jwt.microsoft, or app.jwt.firebaseAuth:

let token = try await req.jwt.apple.verify(applicationIdentifier: appleClientID)

To use req.jwt.apple.verify() without passing the ID each time, configure it first:

app.jwt.apple.applicationIdentifier = appleClientID

For an endpoint that accepts several audience identifiers, use expectedAudiences:

let token = try await req.jwt.google.verify(
    expectedAudiences: [webClientID, mobileClientID]
)

Generic identity-token verification accepts expectedAudience or expectedAudiences and checks signatures using keys registered in app.jwt.keys:

let token = try await req.jwt.verify(
    as: AppleIdentityToken.self,
    expectedAudience: appleClientID
)

At least one expected ID must appear in aud. Any other audience values must be expected IDs or explicitly trusted through trustedAdditionalAudiences.

In Google mobile sign-in, a token requested for a backend server client ID can have that ID in aud and the mobile client ID in azp. Verify the server client ID as the audience. The default does not restrict azp; use trustedAuthorizedPresenters on the Google helper if the application needs to restrict presenting clients.

Authenticating identity tokens

The no-argument JWTPayload.authenticator() uses generic verification and does not check the audience. For an identity token type that conforms to Authenticatable, when the provider’s signing keys are registered in app.jwt.keys, use the audience-aware overload:

let protected = app.grouped(
    AppleIdentityToken.authenticator(expectedAudience: appleClientID),
    AppleIdentityToken.guardMiddleware()
)

If you have a custom JWTAuthenticator whose Payload is an identity token, replace it with a bearer authenticator that checks the audience. When using a provider helper to fetch its signing keys, call that helper with an expected audience. For example, with an AppleUser type conforming to Authenticatable:

struct AppleAuthenticator: AsyncBearerAuthenticator {
    let clientID: String

    func authenticate(bearer: BearerAuthorization, for request: Request) async throws {
        let token = try await request.jwt.apple.verify(bearer.token, applicationIdentifier: clientID)
        request.auth.login(AppleUser(subject: token.subject.value))
    }
}

If no audience is passed or configured, a provider helper still returns a signature-verified token for compatibility and logs a warning. It does not check that the token was issued for your application, so accepting it as a login is insecure. The audience-free req.jwt.verify(as:) and authenticator() calls on concrete identity token types are deprecated. Calls through a generic JWTPayload constraint, including custom JWTAuthenticator types, receive no compile-time warning; successful verification logs a runtime warning.

Pass either applicationIdentifier or expectedAudiences in a provider helper call. An explicit audience list overrides an identifier configured on app.jwt.<provider> for that call.

Topics

Classes

Protocols

Structures

  • struct AppleIdentityToken
  • struct AudienceClaim
    The “aud” (audience) claim identifies the recipients that the JWT is intended for. Each principal intended to process the JWT MUST identify itself with a value in the audience claim. If the principal processing the claim does not identify itself with a value in the “aud” claim when this claim is present, then the JWT MUST be rejected. In the general case, the “aud” value is an array of case- sensitive strings, each containing a StringOrURI value. In the special case when the JWT has one audience, the “aud” value MAY be a single case-sensitive string containing a StringOrURI value. The interpretation of audience values is generally application specific. Use of this claim is OPTIONAL.
  • struct BoolClaim
    A claim which represents a bool
  • struct DefaultJWTParser
  • struct DefaultJWTSerializer
  • struct DigestAlgorithm
  • struct ECDSACurve
    A struct representing an Elliptic Curve used in Elliptic Curve Digital Signature Algorithm (ECDSA).
  • struct EdDSACurve
    A struct representing an Elliptic Curve used in EdDSA (Edwards-curve Digital Signature Algorithm).
  • struct EmptyPolicy
    This Policy acts as a placeholder. Its result is always positive.
  • struct ExpirationClaim
    The “exp” (expiration time) claim identifies the expiration time on or after which the JWT MUST NOT be accepted for processing. The processing of the “exp” claim requires that the current date/time MUST be before the expiration date/time listed in the “exp” claim. Implementers MAY provide for some small leeway, usually no more than a few minutes, to account for clock skew. Its value MUST be a number containing a NumericDate value. Use of this claim is OPTIONAL.
  • struct FirebaseAuthIdentityToken
  • struct GoogleHostedDomainClaim
  • struct GoogleIdentityToken
  • struct HMACKey
  • struct IDClaim
    The “jti” (JWT ID) claim provides a unique identifier for the JWT. The identifier value MUST be assigned in a manner that ensures that there is a negligible probability that the same value will be accidentally assigned to a different data object; if the application uses multiple issuers, collisions MUST be prevented among values produced by different issuers as well. The “jti” claim can be used to prevent the JWT from being replayed. The “jti” value is a case- sensitive string. Use of this claim is OPTIONAL.
  • struct IssuedAtClaim
    The “iat” (issued at) claim identifies the time at which the JWT was issued. This claim can be used to determine the age of the JWT. Its value MUST be a number containing a NumericDate value. Use of this claim is OPTIONAL.
  • struct IssuerClaim
    The “iss” (issuer) claim identifies the principal that issued the JWT. The processing of this claim is generally application specific. The “iss” value is a case-sensitive string containing a StringOrURI value. Use of this claim is OPTIONAL.
  • struct JWK
    A JSON Web Key.
  • struct JWKIdentifier
  • struct JWKS
    A JSON Web Key Set.
  • struct JWTError
    JWT error type.
  • struct JWTHeader
    The header (details) used for signing and processing the JWT.
  • struct LocaleClaim
  • struct MicrosoftIdentityToken
  • struct NotBeforeClaim
    The “nbf” (not before) claim identifies the time before which the JWT MUST NOT be accepted for processing. The processing of the “nbf” claim requires that the current date/time MUST be after or equal to the not-before date/time listed in the “nbf” claim. Implementers MAY provide for some small leeway, usually no more than a few minutes, to account for clock skew. Its value MUST be a number containing a NumericDate value. Use of this claim is OPTIONAL.
  • struct SubjectClaim
    The “sub” (subject) claim identifies the principal that is the subject of the JWT. The claims in a JWT are normally statements about the subject. The subject value MUST either be scoped to be locally unique in the context of the issuer or be globally unique. The processing of this claim is generally application specific. The “sub” value is a case-sensitive string containing a StringOrURI value. Use of this claim is OPTIONAL.
  • struct TenantIDClaim
    The “tid” (tenant ID) claim represents the unique identifier of the Azure AD tenant that the token was issued by. This claim is present in tokens when a user signs in to an application through Azure Active Directory. The tenant ID is a key piece of information for identifying the tenant realm and is essential for applications that are multi-tenant aware. The tenant ID is a GUID that is immutable and uniquely identifies an Azure AD tenant. This claim is crucial for applications that need to enforce tenant-specific access control, and for logging or auditing the tenant context of the authenticated user. The value of “tid” is a case-sensitive string representing a GUID. The presence of this claim and its proper validation are critical for the security of multi-tenant applications.
  • struct X5CValidationTime
    The point in time at which an X5CVerifier validates the x5c certificate chain of a JWS.
  • struct X5CVerifier
    An object for verifying JWS tokens that contain the x5c header parameter with a set of known root certificates.

Type Aliases

Enumerations

  • enum ECDSA
  • enum EdDSA
    Namespace for the EdDSA (Edwards-curve Digital Signature Algorithm) signing algorithm. EdDSA is a modern signing algorithm that is efficient and fast.
  • enum Insecure
    A container for older, cryptographically insecure algorithms.
  • enum JWTHeaderField
  • enum MLDSA
    Namespace for the MLDSA (Module-Lattice-Based Digital Signature Algorithm) signing algorithm.

Extended Modules