Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I generate a JWT to use in API authentication for Swift app

I am trying to implement the use of an API service which requires JWT authentication for all its API calls.

I understand what JWT tokens are and how they are used, my issue is that I am writing a Swift app and can't quite figure out the process to generate the token so that I can attach it as a Bearer in my API calls.

  • Can I generate the JWT token on the client side (swift app)?
  • Create a Google Cloud Function to generate token then write back to Firebase to use in my API calls?
like image 966
Roggie Avatar asked Feb 03 '26 01:02

Roggie


2 Answers

Here's how to make JSON Web Tokens in Swift using Apple's CryptoKit. It uses the default example in https://jwt.io

import CryptoKit

extension Data {
    func urlSafeBase64EncodedString() -> String {
        return base64EncodedString()
            .replacingOccurrences(of: "+", with: "-")
            .replacingOccurrences(of: "/", with: "_")
            .replacingOccurrences(of: "=", with: "")
    }
}

struct Header: Encodable {
    let alg = "HS256"
    let typ = "JWT"
}

struct Payload: Encodable {
    let sub = "1234567890"
    let name = "John Doe"
    let iat = 1516239022
}

let secret = "your-256-bit-secret"
let privateKey = SymmetricKey(data: Data(secret.utf8))

let headerJSONData = try! JSONEncoder().encode(Header())
let headerBase64String = headerJSONData.urlSafeBase64EncodedString()

let payloadJSONData = try! JSONEncoder().encode(Payload())
let payloadBase64String = payloadJSONData.urlSafeBase64EncodedString()

let toSign = Data((headerBase64String + "." + payloadBase64String).utf8)

let signature = HMAC<SHA256>.authenticationCode(for: toSign, using: privateKey)
let signatureBase64String = Data(signature).urlSafeBase64EncodedString()

let token = [headerBase64String, payloadBase64String, signatureBase64String].joined(separator: ".")
print(token) // eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
like image 68
Eric Avatar answered Feb 04 '26 16:02

Eric


It depends on how you plan to sign your token. Fundamentally, you'll want some sort of secret to sign the payload of the JWT.

Is your secret an API key that the client already has? If so, there's not a lot of harm just generating it client side.

Is your secret a certificate that's super secret and you can't give out to clients? Then you'll probably want to go with your Firebase idea.

It's pretty common to just have the client do the signing via API key in these situations, but your motivations for locking down your API to begin with are the driving force here.

IBM-Swift looks like the most complete JWT library for swift these days should you decide to go client side.

Jsonwebtoken is a very good JS one should you decide to deploy a GC Function.

Both libraries are very straightforward to use.

like image 20
ZachChilders Avatar answered Feb 04 '26 16:02

ZachChilders