Authentication

The interviewer asks

“How do you handle authentication in API requests?”

How to answer

Signing in should use passkeys or Sign in with Apple where possible (phishing-resistant, no passwords to leak), or OAuth authorization code + PKCE through ASWebAuthenticationSession for third-party identity providers. The result is a short-lived access token and a refresh token, stored in the Keychain. Every request gets Authorization: Bearer <token> from one place in the networking layer. Refresh is single-flight: an actor holds the in-flight refresh Task, so ten requests that hit a 401 at once trigger one refresh and all retry once with the new token.

Key points

  • Passkeys: ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier:), needs the webcredentials: associated domain; the server verifies the WebAuthn assertion
  • Sign in with Apple: ASAuthorizationAppleIDProvider; send the identity token to your server; check credential state at launch
  • Keychain with kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly (background refresh works, not restored to another device). Never UserDefaults
  • Token provider is an actor holding Task<Token, any Error>?; refresh proactively near expiry and reactively on 401
  • Retry a 401 once; if refresh fails, sign out and clear the Keychain

If they dig deeper

Why an actor and not a lock (callers suspend while the refresh runs; actor reentrancy is why you store the Task rather than a flag). Offering passkeys alongside existing passwords (ASAuthorizationPasswordProvider in the same request, AutoFill-assisted requests). App Attest to prove requests come from your genuine app. Cookie-based sessions (HTTPCookieStorage) vs bearer tokens. Why URLCredential / auth challenges only cover HTTP Basic/Digest/NTLM and client certificates, not bearer tokens.

Common pitfalls

Tokens in UserDefaults, plists or logs. Refresh races that fire N refresh calls and invalidate each other's refresh tokens. Infinite 401 → refresh → 401 loops. Putting the token in httpAdditionalHeaders, which is fixed for the session's lifetime. Embedding a client secret in the app.

How to use it

swift
import Foundation

// nonisolated: encoded and decoded off the main actor
nonisolated struct Token: Codable, Sendable { let access: String; let refresh: String; let expiresAt: Date }

actor TokenProvider {
    private var token: Token?
    private var refreshTask: Task<Token, any Error>?
    private let store: any TokenStore           // Keychain-backed
    private let api: any AuthAPI                // POST /oauth/token

    init(store: any TokenStore, api: any AuthAPI) { self.store = store; self.api = api }

    func validToken() async throws -> Token {
        if let refreshTask { return try await refreshTask.value }      // join in-flight refresh
        guard let current = try token ?? store.load() else { throw AuthError.signedOut }
        if current.expiresAt > .now.addingTimeInterval(30) { return current }
        return try await refresh(using: current)
    }

    func refresh(using old: Token) async throws -> Token {
        if let refreshTask { return try await refreshTask.value }
        if let token, token.access != old.access { return token }     // someone already refreshed
        let task = Task { try await api.refresh(old.refresh) }
        refreshTask = task
        defer { refreshTask = nil }
        do {
            let new = try await task.value
            token = new
            try store.save(new)
            return new
        } catch {
            token = nil; try? store.clear()        // best effort: the refresh error is what we report
            throw error
        }
    }
}
// Client: add "Bearer \(token.access)"; on 401 call refresh(using:) once and retry
swift
import Foundation
import Security

struct KeychainTokenStore: TokenStore {
    let account = "session"
    private var query: [String: Any] {          // Keychain's C API takes a CFDictionary
        [kSecClass as String: kSecClassGenericPassword, kSecAttrAccount as String: account]
    }
    func save(_ token: Token) throws {
        SecItemDelete(query as CFDictionary)
        var item = query
        item[kSecValueData as String] = try JSONEncoder().encode(token)
        item[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
        guard SecItemAdd(item as CFDictionary, nil) == errSecSuccess else { throw AuthError.keychain }
    }
    func load() throws -> Token? {
        var q = query; q[kSecReturnData as String] = true
        var result: CFTypeRef?
        guard SecItemCopyMatching(q as CFDictionary, &result) == errSecSuccess,
              let data = result as? Data else { return nil }
        return try JSONDecoder().decode(Token.self, from: data)
    }
    func clear() throws { SecItemDelete(query as CFDictionary) }
}
swift
import AuthenticationServices

// One sheet offering passkey and Sign in with Apple
@MainActor
func makeSignInController(challenge: Data) -> ASAuthorizationController {
    let passkey = ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: "example.com")
        .createCredentialAssertionRequest(challenge: challenge)   // challenge comes from your server
    let apple = ASAuthorizationAppleIDProvider().createRequest()
    apple.requestedScopes = [.email]
    return ASAuthorizationController(authorizationRequests: [passkey, apple])
}
// Set delegate + presentationContextProvider, call performRequests(), send the result to your server

Best practices

  • Prefer passkeys and Sign in with Apple; use OAuth + PKCE for third-party identity providers
  • Store tokens only in the Keychain, with an accessibility class no weaker than after-first-unlock, this device only
  • Centralize token injection and single-flight refresh in one actor
  • Retry a 401 once, then sign out; clear the Keychain on logout
  • Never log tokens; use os.Logger privacy redaction for anything identifying

Related concepts

  • OAuth 2.0 flow (PKCE), Keychain, headers, request interceptors, actors, App Attest, certificate pinning