### Fetch Apple's JWKS Endpoint Source: https://docs.vapor.codes/4.0/security/jwt Example HTTP GET request to retrieve JSON Web Key Set (JWKS) from Apple's authentication server. This is used for verifying JWTs signed by Apple. ```http GET https://appleid.apple.com/auth/keys ``` -------------------------------- ### Initialize RSA Public Key from PEM Source: https://docs.vapor.codes/4.0/security/jwt Create an RSA public key using its PEM format. RSA keys are in the `Insecure` namespace and should be used for compatibility only. ```swift let rsaPublicKey = """ -----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC0cOtPjzABybjzm3fCg1aCYwnx PmjXpbCkecAWLj/CcDWEcuTZkYDiSG0zgglbbbhcV0vJQDWSv60tnlA3cjSYutAv 7FPo5Cq8FkvrdDzeacwRSxYuIq1LtYnd6I30qNaNthntjvbqyMmBulJ1mzLI+Xg/ aX4rbSL49Z3dAQn8vQIDAQAB -----END PUBLIC KEY----- " // Initialize an RSA key with public pem. let key = try Insecure.RSA.PublicKey(pem: rsaPublicKey) ``` -------------------------------- ### Initialize RSA Private Key with Components Source: https://docs.vapor.codes/4.0/security/jwt Initialize an RSA private key using its modulus, public exponent, and private exponent components. Note that RSA keys smaller than 2048 bits are not supported. ```swift // Initialize an RSA private key with components. let key = try Insecure.RSA.PrivateKey( modulus: modulus, exponent: publicExponent, privateExponent: privateExponent ) ``` -------------------------------- ### Initialize JWK from JSON Source: https://docs.vapor.codes/4.0/security/jwt Create a JSON Web Key (JWK) object from a JSON string. This JWK can then be added to the key collection for signing or verification. ```swift let privateKey = """ { "kty": "RSA", "d": "\(rsaPrivateExponent)", "e": "AQAB", "use": "sig", "kid": "1234", "alg": "RS256", "n": "\(rsaModulus)" } """ let jwk = try JWK(json: privateKey) try await app.jwt.keys.use(jwk: jwk) ``` -------------------------------- ### Google JWT Verification Source: https://docs.vapor.codes/4.0/security/jwt Configure your Google application identifier and G Suite domain name, then use the `req.jwt.google.verify()` helper to fetch and verify a Google JWT. ```APIDOC ## Configure Google App Identifier and Domain ```swift // Configure Google app identifier and domain name. app.jwt.google.applicationIdentifier = "..." app.jwt.google.gSuiteDomainName = "..." ``` ## Fetch and Verify Google JWT ### Description Fetches and verifies a Google JWT from the `Authorization` header. ### Method GET ### Endpoint `/google` ### Response #### Success Response (200) Returns HTTPStatus OK upon successful verification. ### Request Example ```swift // Fetch and verify Google JWT from Authorization header. app.get("google") { req async throws -> HTTPStatus in let token = try await req.jwt.google.verify() print(token) // GoogleIdentityToken return .ok } ``` ``` -------------------------------- ### Configure Google App Identifier and Domain for JWT Source: https://docs.vapor.codes/4.0/security/jwt Set the application identifier and G Suite domain name for Google JWT authentication. These are necessary for token verification. ```swift // Configure Google app identifier and domain name. app.jwt.google.applicationIdentifier = "..." app.jwt.google.gSuiteDomainName = "..." ``` -------------------------------- ### Initialize ECDSA Public Key from PEM Source: https://docs.vapor.codes/4.0/security/jwt Initializes an ECDSA public key from a PEM-formatted string. This key can be used for verifying JWT signatures. ```swift let ecdsaPublicKey = """ -----BEGIN PUBLIC KEY----- MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2adMrdG7aUfZH57aeKFFM01dPnkx C18ScRb4Z6poMBgJtYlVtd9ly63URv57ZW0Ncs1LiZB7WATb3svu+1c7HQ== -----END PUBLIC KEY----- """ // Initialize an ECDSA key with public PEM. let key = try ES256PublicKey(pem: ecdsaPublicKey) ``` -------------------------------- ### Initialize EdDSA Public Key Source: https://docs.vapor.codes/4.0/security/jwt Initializes an EdDSA public key using its base-64 encoded x-coordinate and the specified curve. ```swift let publicKey = try EdDSA.PublicKey(x: "0ZcEvMCSYqSwR8XIkxOoaYjRQSAO8frTMSCpNbUl4lE", curve: .ed25519) ``` -------------------------------- ### Microsoft JWT Verification Source: https://docs.vapor.codes/4.0/security/jwt Configure your Microsoft application identifier and then use the `req.jwt.microsoft.verify()` helper to fetch and verify a Microsoft JWT. ```APIDOC ## Configure Microsoft App Identifier ```swift // Configure Microsoft app identifier. app.jwt.microsoft.applicationIdentifier = "..." ``` ## Fetch and Verify Microsoft JWT ### Description Fetches and verifies a Microsoft JWT from the `Authorization` header. ### Method GET ### Endpoint `/microsoft` ### Response #### Success Response (200) Returns HTTPStatus OK upon successful verification. ### Request Example ```swift // Fetch and verify Microsoft JWT from Authorization header. app.get("microsoft") { req async throws -> HTTPStatus in let token = try await req.jwt.microsoft.verify() print(token) // MicrosoftIdentityToken return .ok } ``` ``` -------------------------------- ### Apple JWT Verification Source: https://docs.vapor.codes/4.0/security/jwt Configure your Apple application identifier and then use the `req.jwt.apple.verify()` helper to fetch and verify an Apple JWT from the Authorization header. ```APIDOC ## Configure Apple App Identifier ```swift // Configure Apple app identifier. app.jwt.apple.applicationIdentifier = "..." ``` ## Fetch and Verify Apple JWT ### Description Fetches and verifies an Apple JWT from the `Authorization` header. ### Method GET ### Endpoint `/apple` ### Response #### Success Response (200) Returns HTTPStatus OK upon successful verification. ### Request Example ```swift // Fetch and verify Apple JWT from Authorization header. app.get("apple") { req async throws -> HTTPStatus in let token = try await req.jwt.apple.verify() print(token) // AppleIdentityToken return .ok } ``` ``` -------------------------------- ### Initialize EdDSA Private Key Source: https://docs.vapor.codes/4.0/security/jwt Initializes an EdDSA private key using its base-64 encoded d-coordinate and the specified curve. ```swift let privateKey = try EdDSA.PrivateKey(d: "d1H3/dcg0V3XyAuZW2TE5Z3rhY20M+4YAfYu/HUQd8w=", curve: .ed25519) ``` -------------------------------- ### Verify Microsoft JWT Source: https://docs.vapor.codes/4.0/security/jwt Fetch and verify a Microsoft JWT from the Authorization header. This helper method simplifies the process of validating Microsoft identity tokens. ```swift // Fetch and verify Microsoft JWT from Authorization header. app.get("microsoft") { req async throws -> HTTPStatus in let token = try await req.jwt.microsoft.verify() print(token) // MicrosoftIdentityToken return .ok } ``` -------------------------------- ### Add JWT Dependency to Package.swift Source: https://docs.vapor.codes/4.0/security/jwt Include the JWT package in your project's Package.swift file to use JWT functionality. ```swift // swift-tools-version:5.10 import PackageDescription let package = Package( name: "my-app", dependencies: [ // Other dependencies... .package(url: "https://github.com/vapor/jwt.git", from: "5.0.0"), ], targets: [ .target(name: "App", dependencies: [ // Other dependencies... .product(name: "JWT", package: "jwt") ]), // Other targets... ] ) ``` -------------------------------- ### Verifying JWT from Incoming Request Source: https://docs.vapor.codes/4.0/security/jwt This snippet demonstrates how to verify a JWT from an incoming request's `Authorization` header. The `req.jwt.verify` helper automatically parses the token, verifies its signature and claims, and throws a 401 error if any step fails. The verified payload can then be used within your application. ```APIDOC ## GET /me ### Description Verifies the JWT from the `Authorization` header and returns the payload. ### Method GET ### Endpoint `/me` ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```http GET /me HTTP/1.1 Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ2YXBvciIsImV4cCI6NjQwOTIyMTEyMDAsImFkbWluIjp0cnVlfQ.lS5lpwfRNSZDvpGQk6x5JI1g40gkYCOWqbc3J_ghowo ``` ### Response #### Success Response (200) Returns `200 OK` if the JWT is valid. The payload is printed to the console. #### Response Example ```json TestPayload( subject: "vapor", expiration: 4001-01-01 00:00:00 +0000, isAdmin: true ) ``` ``` -------------------------------- ### Verify JWT from Incoming Request Source: https://docs.vapor.codes/4.0/security/jwt Fetches and verifies a JWT from the Authorization header of an incoming request. Throws a 401 Unauthorized error if verification fails. ```swift // Fetch and verify JWT from incoming request. app.get("me") { req async throws -> HTTPStatus in let payload = try await req.jwt.verify(as: TestPayload.self) print(payload) return .ok } ``` -------------------------------- ### Configure Microsoft App Identifier for JWT Source: https://docs.vapor.codes/4.0/security/jwt Specify the application identifier for Microsoft JWT authentication. This configuration is a prerequisite for verifying Microsoft tokens. ```swift // Configure Microsoft app identifier. app.jwt.microsoft.applicationIdentifier = "..." ``` -------------------------------- ### Adding ECDSA Keys Source: https://docs.vapor.codes/4.0/security/jwt This section covers adding ECDSA keys, which use asymmetric cryptography (public/private key pairs). Vapor supports ES256, ES384, and ES512 algorithms. Keys can be added from PEM format or generated randomly. ```APIDOC ## Add ECDSA Key ### Description Adds an ECDSA key pair for asymmetric signing and verification. ### Method `app.jwt.keys.add` overload for ECDSA ### Parameters - **ecdsa** (ECDSAKey) - An instance of `ES256PublicKey`, `ES384PublicKey`, `ES512PublicKey`, `ES256PrivateKey`, `ES384PrivateKey`, or `ES512PrivateKey`. ### Code Example (from PEM) ```swift let ecdsaPublicKey = """ -----BEGIN PUBLIC KEY----- MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2adMrdG7aUfZH57aeKFFM01dPnkx C18ScRb4Z6poMBgJtYlVtd9ly63URv57ZW0Ncs1LiZB7WATb3svu+1c7HQ== -----END PUBLIC KEY----- """ // Initialize an ECDSA key with public PEM. let key = try ES256PublicKey(pem: ecdsaPublicKey) await app.jwt.keys.add(ecdsa: key) ``` ### Code Example (generated) ```swift // Generate a random private key. let key = ES256PrivateKey() await app.jwt.keys.add(ecdsa: key) ``` ``` -------------------------------- ### Adding EdDSA Keys Source: https://docs.vapor.codes/4.0/security/jwt This section details how to add EdDSA keys, another asymmetric algorithm based on Edwards-curve. Vapor supports the EdDSA algorithm using the Ed25519 curve. Keys can be created from coordinates or generated randomly. ```APIDOC ## Add EdDSA Key ### Description Adds an EdDSA key pair for asymmetric signing and verification using the Ed25519 curve. ### Method `app.jwt.keys.add` overload for EdDSA ### Parameters - **eddsa** (EdDSAKey) - An instance of `EdDSA.PublicKey` or `EdDSA.PrivateKey`. ### Code Example (from coordinates) ```swift let publicKey = try EdDSA.PublicKey(x: "0ZcEvMCSYqSwR8XIkxOoaYjRQSAO8frTMSCpNbUl4lE", curve: .ed25519) let privateKey = try EdDSA.PrivateKey(d: "d1H3/dcg0V3XyAuZW2TE5Z3rhY20M+4YAfYu/HUQd8w=", curve: .ed25519) await app.jwt.keys.add(eddsa: privateKey) ``` ### Code Example (generated) ```swift // Generate a random private key. let key = EdDSA.PrivateKey(curve: .ed25519) await app.jwt.keys.add(eddsa: key) ``` ``` -------------------------------- ### Add HMAC Key with Kid Source: https://docs.vapor.codes/4.0/security/jwt Add an HMAC key with a specified digest algorithm and a key identifier (kid). If no kid is provided, it becomes the default key. ```swift // Add HMAC with SHA-256 key named "a". await app.jwt.keys.add(hmac: "foo", digestAlgorithm: .sha256, kid: "a") ``` -------------------------------- ### Verify Apple JWT Source: https://docs.vapor.codes/4.0/security/jwt Fetch and verify an Apple JWT from the Authorization header. This helper simplifies the process of validating user identity. ```swift // Fetch and verify Apple JWT from Authorization header. app.get("apple") { req async throws -> HTTPStatus in let token = try await req.jwt.apple.verify() print(token) // AppleIdentityToken return .ok } ``` -------------------------------- ### Adding HMAC Keys Source: https://docs.vapor.codes/4.0/security/jwt This section explains how to add HMAC keys for signing and verifying JWTs. HMAC is a symmetric algorithm requiring a shared secret. Vapor supports HS256, HS384, and HS512. ```APIDOC ## Add HMAC Key ### Description Adds a secret key for HMAC signing and verification. ### Method `app.jwt.keys.add` overload for HMAC ### Parameters - **hmac** (String) - The secret key string. - **digestAlgorithm** (HMACDigestAlgorithm) - The SHA algorithm to use (e.g., `.sha256`, `.sha384`, `.sha512`). ### Code Example ```swift // Add an HS256 key. await app.jwt.keys.add(hmac: "secret", digestAlgorithm: .sha256) ``` ``` -------------------------------- ### Add Multiple JWKs from JSON Source: https://docs.vapor.codes/4.0/security/jwt Add multiple JSON Web Keys (JWKs) to the key collection by providing a JSON string containing an array of keys. This is useful for managing multiple signing keys. ```swift let json = """ { "keys": [ {"kty": "RSA", "alg": "RS256", "kid": "a", "n": "\(rsaModulus)", "e": "AQAB"}, {"kty": "RSA", "alg": "RS512", "kid": "b", "n": "\(rsaModulus)", "e": "AQAB"}, ] } """ try await app.jwt.keys.use(jwksJSON: json) ``` -------------------------------- ### Configure Apple App Identifier for JWT Source: https://docs.vapor.codes/4.0/security/jwt Set the application identifier for Apple JWT authentication. This is required before verifying tokens. ```swift // Configure Apple app identifier. app.jwt.apple.applicationIdentifier = "..." ``` -------------------------------- ### Define Custom JWT Payload Structure Source: https://docs.vapor.codes/4.0/security/jwt Create a custom structure conforming to JWTPayload to define the data and verification logic for your JWTs. This includes mapping Swift property names to JWT claim keys and implementing custom verification. ```swift // JWT payload structure. struct TestPayload: JWTPayload { // Maps the longer Swift property names to the // shortened keys used in the JWT payload. enum CodingKeys: String, CodingKey { case subject = "sub" case expiration = "exp" case isAdmin = "admin" } // The "sub" (subject) claim identifies the principal that is the // subject of the JWT. var subject: SubjectClaim // The "exp" (expiration time) claim identifies the expiration time on // or after which the JWT MUST NOT be accepted for processing. var expiration: ExpirationClaim // Custom data. // If true, the user is an admin. var isAdmin: Bool // Run any additional verification logic beyond // signature verification here. // Since we have an ExpirationClaim, we will // call its verify method. func verify(using algorithm: some JWTAlgorithm) async throws { try self.expiration.verifyNotExpired() } } ``` -------------------------------- ### Verify Google JWT Source: https://docs.vapor.codes/4.0/security/jwt Fetch and verify a Google JWT from the Authorization header. This function streamlines the validation of Google identity tokens. ```swift // Fetch and verify Google JWT from Authorization header. app.get("google") { req async throws -> HTTPStatus in let token = try await req.jwt.google.verify() print(token) // GoogleIdentityToken return .ok } ``` -------------------------------- ### Generate Random ECDSA Private Key Source: https://docs.vapor.codes/4.0/security/jwt Generates a new random ECDSA private key. Useful for testing purposes when a real key is not required. ```swift let key = ES256PrivateKey() ``` -------------------------------- ### Configure HMAC Key for JWT Source: https://docs.vapor.codes/4.0/security/jwt Add an HMAC key with SHA-256 digest algorithm to the JWT key collection in your application's configuration. ```swift import JWT // Add HMAC with SHA-256 signer. await app.jwt.keys.add(hmac: "secret", digestAlgorithm: .sha256) ``` -------------------------------- ### Add HMAC Key for JWT Signing Source: https://docs.vapor.codes/4.0/security/jwt Adds an HMAC secret key to the keychain for signing JWTs using the HS256 algorithm. ```swift // Add an HS256 key. await app.jwt.keys.add(hmac: "secret", digestAlgorithm: .sha256) ``` -------------------------------- ### Sign JWT with Specific Kid Source: https://docs.vapor.codes/4.0/security/jwt Sign a JWT payload using a specific key identifier (kid) from the key collection. ```swift let token = try await req.jwt.sign(payload, kid: "a") ``` -------------------------------- ### Generate Random EdDSA Private Key Source: https://docs.vapor.codes/4.0/security/jwt Generates a new random EdDSA private key for the Ed25519 curve. Useful for testing. ```swift let key = EdDSA.PrivateKey(curve: .ed25519) ``` -------------------------------- ### Add RSA Key to Key Collection Source: https://docs.vapor.codes/4.0/security/jwt Add an RSA key to the application's JWT key collection, specifying the digest algorithm. This key can then be used for signing and verifying JWTs. ```swift await app.jwt.keys.add(rsa: key, digestAlgorithm: .sha256) ``` -------------------------------- ### Add EdDSA Key to Keychain Source: https://docs.vapor.codes/4.0/security/jwt Adds an EdDSA key to the application's keychain for JWT signing or verification. ```swift await app.jwt.keys.add(eddsa: key) ``` -------------------------------- ### Sign JWT Payload in Route Handler Source: https://docs.vapor.codes/4.0/security/jwt Sign a custom JWT payload within a Vapor route handler. The signed token is returned as a string in the response. ```swift app.post("login") { req async throws -> [String: String] in let payload = TestPayload( subject: "vapor", expiration: .init(value: .distantFuture), isAdmin: true ) return try await ["token": req.jwt.sign(payload)] } ``` -------------------------------- ### Add ECDSA Key to Keychain Source: https://docs.vapor.codes/4.0/security/jwt Adds an ECDSA key (public or private) to the application's keychain for JWT signing or verification. ```swift await app.jwt.keys.add(ecdsa: key) ``` -------------------------------- ### Add PSS Key to Key Collection Source: https://docs.vapor.codes/4.0/security/jwt Add an RSA-PSS key to the JWT key collection, specifying the digest algorithm. PSS is a more secure padding scheme than PKCS1v1.5. ```swift await app.jwt.keys.add(pss: key, digestAlgorithm: .sha256) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.