JWTDecode.swift

repository·master·Indexed 20 days ago

https://github.com/auth0/jwtdecode.swift

A lightweight Swift library for decoding JSON Web Tokens (JWT). It extracts headers, claims, and signatures from well-formed JWTs without performing cryptographic validation. The library is compatible with Swift 6 concurrency, with all public types conforming to Sendable. It supports installation via Swift Package Manager, CocoaPods, and Carthage.

Tokens
2.3K
Snippets
12
Records
19
Agent score
71%

What's inside JWTDecode.swift

  1. Migrate to JWTDecode.swift v4

    master
    JWTDecode.swift v4 introduces breaking changes to support Swift 6 concurrency. The primary change is that all public types, including the JWT protocol and the Claim struct, now conform to Sendable. Additionally, dictionary values for header, body, and Claim.rawValue have changed from Any to any Sendable.
  2. Migrate to JWTDecode.swift v3

    master
    JWTDecode.swift v3 is a major release containing breaking changes. To migrate, you must update your deployment targets, ensure your Swift version is compatible, and update references to renamed types and properties. Note that Objective-C support has been removed.
  3. Install JWTDecode.swift

    master

    You can install JWTDecode.swift using Swift Package Manager, CocoaPods, or Carthage.

    Swift Package Manager

    1. In Xcode, go to File > Add Packages...
    2. Enter the URL: https://github.com/auth0/JWTDecode.swift
    3. Select your dependency rule and press Add Package.

    CocoaPods

    Add this line to your Podfile:

    pod 'JWTDecode', '~> 4.0'

    Then run pod install.

    Carthage

    Add this line to your Cartfile:

    github "auth0/JWTDecode.swift" ~> 4.0

    Then run carthage bootstrap --use-xcframeworks.

  4. Decode a JWT token

    master

    To use the library, import the framework and use the decode(jwt:) function.

    Important: This library does not validate the JWT signature; it only decodes the Base64URL encoded parts. Any well-formed JWT can be decoded.

    All public types conform to Sendable, making the library fully compatible with Swift 6 concurrency.

    import JWTDecode
    
    // Decode the token
    let jwt = try decode(jwt: token)
  5. Access JWT parts and registered claims

    master

    Once a JWT is decoded, you can access its components and standard registered claims through specific properties on the JWT object.

    JWT Parts

    PartProperty
    Header dictionaryjwt.header
    Claims in JWT bodyjwt.body
    JWT signaturejwt.signature

    Registered Claims

    ClaimProperty
    aud Audiencejwt.audience
    sub Subjectjwt.subject
    jti JWT IDjwt.identifier
    iss Issuerjwt.issuer
    nbf Not Beforejwt.notBefore
    iat Issued Atjwt.issuedAt
    exp Expiration Timejwt.expiresAt
  6. Access claim data as Data

    master

    The new .data property on a Claim allows you to retrieve the underlying JSON representation as Data. This is only available for complex claims (arrays and dictionaries). For primitive types (strings, integers, etc.), .data will return nil.

    // Returns Data for arrays and dictionaries
    let data = jwt["custom_object"].data
    
    // Returns nil for primitives (use .string, .integer, etc. instead)
    let primitiveData = jwt["email"].data // nil
  7. Retrieve custom claims

    master

    You can retrieve custom claims using subscript syntax. The library provides several built-in type conversions or allows decoding directly into Decodable types.

    Supported Type Conversions

    • string: String?
    • boolean: Bool?
    • integer: Int?
    • double: Double?
    • date: Date?
    • array: [String]?
    • data: Data?

    Decoding to Decodable types

    You can decode complex claims directly to a Decodable type, including using a custom JSONDecoder for specific configurations like keyDecodingStrategy.

    // Retrieve a simple string claim
    if let email = jwt["email"].string {
        print("Email is \(email)")
    }
    
    // Decode a custom claim to a Decodable struct
    struct Address: Decodable {
        let street: String
        let city: String
    }
    let address = try jwt["address"].decode(Address.self)
    
    // Decode with a custom JSONDecoder configuration
    struct User: Decodable {
        let firstName: String
        let lastName: String
    }
    let decoder = JSONDecoder()
    decoder.keyDecodingStrategy = .convertFromSnakeCase
    let user = try jwt["user_info"].decode(User.self, using: decoder)
  8. Decode complex claims to Decodable types

    master

    In v4, you can decode complex claims (like dictionaries or arrays) directly into a Swift type that conforms to Decodable using the .decode(_:using:) method on a Claim object.

    struct Address: Decodable {
        let street: String
        let city: String
    }
    
    // Decode a custom claim
    let address = try jwt["address"].decode(Address.self)
    
    // With custom decoder configuration
    let decoder = JSONDecoder()
    decoder.keyDecodingStrategy = .convertFromSnakeCase
    let userInfo = try jwt["user_info"].decode(UserInfo.self, using: decoder)
  9. Update type annotations for JWT Header and Body

    master

    If your code directly accesses the header or body properties of a JWT object, you must update the type annotations from [String: Any] to [String: any Sendable] to maintain compatibility with v4.

    // Before (v3)
    let header: [String: Any] = jwt.header
    let body: [String: Any] = jwt.body
    
    // After (v4)
    let header: [String: any Sendable] = jwt.header
    let body: [String: any Sendable] = jwt.body