JWT Tokens in Swift: Working with JSON Web Token on iOS/macOS

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

JWT Tokens in Swift (iOS/macOS): Complete Guide



JSON Web Token (JWT) is an open standard (RFC 7519) for creating access tokens based on JSON. JWT is widely used for authentication and information exchange between client and server. In the Apple ecosystem (iOS, macOS, watchOS, tvOS), working with JWT becomes critically important when developing applications that interact with REST APIs, microservices, or any systems requiring secure data transfer.



This article is dedicated to the SwiftJWT library — the most popular and actively maintained solution for working with JWT in Swift. We will cover installation, basic operations (creation, signing, verification), and advanced usage scenarios.



What is SwiftJWT?



SwiftJWT is a lightweight, native library for Swift that allows you to:

  • Create JWT with arbitrary claims
  • Sign tokens using algorithms: HS256, HS384, HS512 (symmetric) and RS256, RS384, RS512 (asymmetric, RSA-based)
  • Verify the signature and expiration date of the token
  • Decode the payload without signature verification (e.g., for displaying information on the client)
  • Work with custom data and standard fields (iss, sub, exp, iat, etc.)


The library is written entirely in Swift, requires no external dependencies (except Foundation and Security), and is compatible with Swift Package Manager (SPM), CocoaPods, and Carthage.



Installation via Swift Package Manager



Add the package to your project via Xcode or directly in Package.swift:



// Package.swiftdependencies: [    .package(url: "https://github.com/Kitura/Swift-JWT.git", from: "4.0.0")],targets: [    .target(name: "YourTarget", dependencies: ["SwiftJWT"])]


Basic JWT Operations



1. Creating and Signing a Token (HS256)



The simplest case — creating a token using a symmetric key:



import SwiftJWT

// 1. Define the Claims structurestruct MyClaims: Claims { let iss: String let sub: String let exp: Date let admin: Bool let customData: String}

// 2. Create a Claims instancelet claims = MyClaims( iss: "com.yourcompany.app", sub: "user123", exp: Date(timeIntervalSinceNow: 3600), // +1 hour admin: true, customData: "some_value")

// 3. Define the key (for HS256 — any string)let secretKey = "your-256-bit-secret".data(using: .utf8)!

// 4. Create the JWTvar jwt = JWT(claims: claims)let signedJWT = try jwt.sign(using: .hs256(key: secretKey))print("Created token:\\(signedJWT)")


2. Verifying and Decoding a Token



// Verification with signature and expiration checklet receivedToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."

do { // Verify and decode let verifiedJWT = try JWT<MyClaims>.verify(token: receivedToken, using: .hs256(key: secretKey)) print("Token is valid. Claims: \\(verifiedJWT.claims)") // Check specific fields if verifiedJWT.claims.admin { print("User is an administrator") }} catch { print("Verification error: \\(error)") // Possible errors: expiredToken, invalidSignature, malformedToken}

// Decoding without verification (read-only data)if let payload = try? JWTDecoder().decodePayload(from: receivedToken) { print("Payload (without verification): \\(payload)")}


3. Working with Asymmetric Keys (RS256)



For production environments, it is recommended to use asymmetric encryption (RSA). The server signs the token with a private key, and the client verifies it with a public key:



//                    

Recommendations