Swift / iOS JWT generator quickstart
Create a token with your public API key in the sub claim, a near-term Unix timestamp in exp, and an HS256 signature made with your private API key.
Sapling JWTs use HS256 with a
sub claim containing your public API key and an exp claim containing a Unix timestamp. The examples use a one-hour lifetime; shorten it further when your application can refresh tokens easily.
Swift / iOS
HS256 · sub + exp
This example uses JWTKit 5 with Swift 6 or newer.
import Foundation
import JWTKit
struct SaplingClaims: JWTPayload {
let sub: SubjectClaim
let exp: ExpirationClaim
func verify(using algorithm: some JWTAlgorithm) async throws {
try exp.verifyNotExpired()
}
}
@main
struct Main {
static func main() async throws {
guard let publicKey = ProcessInfo.processInfo.environment["SAPLING_PUBLIC_KEY"],
let privateKey = ProcessInfo.processInfo.environment["SAPLING_PRIVATE_KEY"] else {
throw NSError(
domain: "Quickstart",
code: 1,
userInfo: [
NSLocalizedDescriptionKey:
"Set SAPLING_PUBLIC_KEY and SAPLING_PRIVATE_KEY first."
]
)
}
let keys = JWTKeyCollection()
await keys.add(hmac: privateKey, digestAlgorithm: .sha256)
let claims = SaplingClaims(
sub: SubjectClaim(value: publicKey),
exp: ExpirationClaim(value: Date().addingTimeInterval(3600))
)
print(try await keys.sign(claims))
}
}
Generated token
text/plain
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.<base64url-claims>.<signature>
Return the compact token to the browser and pass it to Sapling.init as the key. Issue a fresh token after it expires; never send the private key.
About Swift / iOS
Swift is a compiled programming language developed by Apple as a replacement for Objective-C. It is used with Cocoa and Cocoa Touch frameworks for application development for iOS and macOS platforms.