Clavem

How to validate a license key in a Swift app

POST the key and the stored instance id to /v1/licenses/validate with URLSession, then branch on the HTTP status and the valid field. Keep the key in the Keychain and give the request an 8-second timeout, so a bad network cannot hold up launch.

The call

Validation is one POST. Send license_key, and instance_id once the Mac has activated (see device activation in Swift). The client below turns every answer into a four-case enum, so the rest of the app never looks at status codes.

import Foundation

enum ValidationOutcome {
  case valid(token: String)
  case notValid(reason: String, token: String?)   // 200 with valid: false (expired or disabled)
  case unknown(reason: String)                    // 404: the key or this Mac's activation is gone
  case noAnswer(retryAfter: TimeInterval?)        // offline, timeout, 429, 5xx
}

actor LicenseClient {
  private let base: URL
  private let session: URLSession

  init(base: URL = URL(string: "https://clavem.io")!) {
    self.base = base
    let config = URLSessionConfiguration.ephemeral
    config.timeoutIntervalForRequest = 8
    config.waitsForConnectivity = false
    session = URLSession(configuration: config)
  }

  func validate(key: String, instanceID: String?) async -> ValidationOutcome {
    var body = ["license_key": key]
    if let instanceID { body["instance_id"] = instanceID }

    var request = URLRequest(url: base.appendingPathComponent("v1/licenses/validate"))
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.httpBody = try? JSONSerialization.data(withJSONObject: body)

    guard let (data, response) = try? await session.data(for: request),
          let http = response as? HTTPURLResponse else { return .noAnswer(retryAfter: nil) }
    let json = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] ?? [:]
    let message = json["error"] as? String ?? "This license is not valid."

    switch http.statusCode {
    case 200:
      guard let valid = json["valid"] as? Bool else { return .noAnswer(retryAfter: nil) }
      let token = json["token"] as? String
      if valid, let token { return .valid(token: token) }
      return .notValid(reason: message, token: token)
    case 404:
      return .unknown(reason: message)
    case 429, 503:
      return .noAnswer(retryAfter: http.value(forHTTPHeaderField: "Retry-After").flatMap(TimeInterval.init))
    default:
      return .noAnswer(retryAfter: nil)
    }
  }
}

What each answer means

Answer Outcome What the app does
200, valid: true .valid Store the new token, which restarts the 14-day window. Turn the paid features on.
200, valid: false .notValid Expired or disabled. Store the token, show error, keep the key: a renewal can revive it.
404 .unknown Unknown key, or instance_id not found. Clear the stored license and ask for the key.
429 or 503 .noAnswer Not a verdict on the license. Use the stored token and try again later.
No response .noAnswer Same as above.

A 400 means your request was malformed, so it is a bug in the app and not something to show a customer.

Real answers from the demo key

This is the output of the client above, run against the live API with the public demo key (and a local stub for the two limit cases):

demo key: valid (token sgt1.eyJ2Ijo...)
unknown key: unknown(license_key not found.)
demo key, unknown instance: unknown(instance_id not found.)
stub TEST-429: noAnswer(retryAfter: 60)
stub TEST-503 with retry: noAnswer(retryAfter: 5) after 5.0 s

The live responses carry Cache-Control: no-store and Access-Control-Allow-Origin: *, so nothing in URLSession caches a verdict.

Where to keep the key

Use the Keychain. One generic-password item per value keeps the key, the instance id and the token separate:

import Security

struct KeychainStore {
  let service: String   // your bundle identifier plus ".license"

  private func query(_ account: String) -> [String: Any] {
    [kSecClass as String: kSecClassGenericPassword,
     kSecAttrService as String: service, kSecAttrAccount as String: account]
  }

  func set(_ value: String, for account: String) {
    let data = Data(value.utf8)
    if SecItemUpdate(query(account) as CFDictionary, [kSecValueData as String: data] as CFDictionary) == errSecItemNotFound {
      let add = query(account).merging([kSecValueData as String: data,
        kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlock]) { $1 }
      SecItemAdd(add as CFDictionary, nil)
    }
  }

  func get(_ account: String) -> String? {
    let request = query(account).merging([kSecReturnData as String: true,
      kSecMatchLimit as String: kSecMatchLimitOne]) { $1 }
    var item: CFTypeRef?
    guard SecItemCopyMatching(request as CFDictionary, &item) == errSecSuccess,
          let data = item as? Data else { return nil }
    return String(data: data, encoding: .utf8)
  }

  func remove(_ account: String) { SecItemDelete(query(account) as CFDictionary) }
}

kSecAttrAccessibleAfterFirstUnlock lets a login item read the key after a restart, as soon as the user has signed in once. Update the item in place when it exists, and add it only when SecItemUpdate returns errSecItemNotFound.

Keychain access control is tied to your code signature. A build signed with a different identity can trigger a password prompt on first read, so test an update from an old signed build to a new one before you ship.

When there is no answer

A 503 carries Retry-After: 5. A 429 carries Retry-After: 60. Do not hold a launch for 60 seconds. Retry once for the short wait, give up on the long one, and fall back to the stored token (the check is on the offline verification page):

extension LicenseClient {
  func validateWithRetry(key: String, instanceID: String?) async -> ValidationOutcome {
    var outcome = await validate(key: key, instanceID: instanceID)
    if case .noAnswer(let wait?) = outcome, wait <= 5 {
      try? await Task.sleep(nanoseconds: UInt64(wait * 1_000_000_000))
      outcome = await validate(key: key, instanceID: instanceID)
    }
    return outcome
  }
}

Call it from a .task on your root view, not from applicationDidFinishLaunching before the window appears. The app is usable while the request runs.

Pitfalls in Swift

  • Leave waitsForConnectivity off. With it on, a request waits for a connection instead of failing, and your launch waits with it. Apple documents the two behaviours: wait, or fail immediately.
  • Sandboxed apps need com.apple.security.network.client. Without it every call fails.
  • as? Int and as? Bool on JSONSerialization output are fine, but a field that is null fails the cast. error is null on success, so read it only on the failure paths.
  • Use ephemeral, not .shared. A separate session has its own timeout and no cookie jar.
  • Do not log the key. print(request) shows the body in debug builds.

Doing this with Clavem

The License API needs no secret: the key is the credential, so nothing sensitive ships in your app. Plan limits never block validation. Every field is in the API reference, and the Swift guide in the docs has the same flow in one file. Activation, deactivation and update checks are covered in device activation and software updates.

Questions

Where should a macOS app store a license key?

In the Keychain, as a generic password item. UserDefaults is a plain property list that anyone can read and edit. Use the kSecAttrAccessibleAfterFirstUnlock attribute so a launch at login can still read it.

Does a sandboxed Mac app need an entitlement to call the License API?

Yes. A sandboxed app needs the com.apple.security.network.client entitlement to open outgoing connections. Without it the request fails before it leaves the Mac.

Should validation block the app launching?

No. Show the app, trust the stored token while it is fresh, and validate in the background with a short timeout. Only a 404 or valid false should take features away.

Sources

  1. Apple, waitsForConnectivity (checked November 2026)
  2. Apple, kSecAttrAccessibleAfterFirstUnlock (checked November 2026)
  3. Apple, com.apple.security.network.client entitlement (checked November 2026)