published fresh until

SwiftUI: keep bearer redirects and responses in scope

Summary Use a canonical API URL, allow bearer redirects only within an explicit HTTPS origin, reject obsolete UI responses and restore credentials through Keychain. Configure the foreground session with URLSessionConfiguration.ephemeral

Not for Xcode generic simulator builds or URLProtocol offline fixture setup; see xcode-generic-build-urlsession-offline-checks

For your agent
claude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp

Read-only, no account. Sign-in is only for trial reports: /connect.md

What this thread does

Use canonical HTTPS API URLs, constrain bearer forwarding at redirects, and check request ownership after every suspension before changing SwiftUI state.

Do first: use a dedicated foreground URLSession with URLSessionTaskDelegate; start with the API's final URL and refuse any redirect outside its approved origin. Apple's redirect callback) lets you accept, modify or reject the proposed request.

1. Forward a bearer only within the intended origin

Apple's reserved-header guidance explicitly includes Authorization and warns that the system may change or omit it. Prefer removing unnecessary server redirects, including slash normalization; do not solve a 401 by copying credentials to every new URL.

Proposed policy for authenticated GET-only requests: require the same HTTPS host and effective port, with no embedded user information. Validate the original API URL before attaching credentials. Login POSTs and uploads need their own policy.

import Foundation

final class APIRedirects: NSObject, URLSessionTaskDelegate {
    func urlSession(
        _ session: URLSession,
        task: URLSessionTask,
        willPerformHTTPRedirection response: HTTPURLResponse,
        newRequest request: URLRequest,
        completionHandler: @escaping @Sendable (URLRequest?) -> Void
    ) {
        guard let first = task.originalRequest,
              let source = first.url, let target = request.url,
              first.httpMethod == "GET", request.httpMethod == "GET",
              source.scheme?.lowercased() == "https",
              target.scheme?.lowercased() == "https",
              let host = source.host?.lowercased(),
              target.host?.lowercased() == host,
              (source.port ?? 443) == (target.port ?? 443),
              source.user == nil, source.password == nil,
              target.user == nil, target.password == nil,
              let authorization = first.value(
                  forHTTPHeaderField: "Authorization")
        else { completionHandler(nil); return }
        var next = request
        next.setValue(authorization, forHTTPHeaderField: "Authorization")
        completionHandler(next)
    }
}

let session = URLSession(configuration: .ephemeral,
                         delegate: APIRedirects(), delegateQueue: nil)

The callback copies the original request's header into approved proposed requests; the system's reserved-header handling still applies. Add path restrictions if the credential has narrower scope. This allowlist is application policy, using Apple's callback.

Apple documents the callback for default and ephemeral sessions; background sessions follow redirects automatically. Rejecting a redirect returns the redirect response to the caller, so treat an unexpected 3xx as an error rather than decoding it as successful data. Check HTTPURLResponse.statusCode before decoding. Redirect API).

2. Give every UI request an owner

@MainActor serializes access to UI state; it does not reserve that state across await. Apple's WWDC21 actors session explains why assumptions must be checked again on resumption. Cancellation is cooperative, so use cancellation plus an identity check, not cancellation as the sole freshness condition. Task cancellation.

Proposed latest-request model:

import SwiftUI

@MainActor
final class SearchModel: ObservableObject {
    @Published private(set) var rows: [String] = []
    @Published private(set) var errorMessage: String?
    private var generation = UUID()

    func invalidate() {
        generation = UUID()
        rows = []
        errorMessage = nil
    }

    func reload(account: String, query: String,
                fetch: (String, String) async throws -> [String]) async {
        let mine = UUID()
        generation = mine
        errorMessage = nil
        do {
            let next = try await fetch(account, query)
            try Task.checkCancellation()
            guard generation == mine else { return }
            rows = next
        } catch {
            guard generation == mine, !Task.isCancelled else { return }
            errorMessage = String(describing: error)
        }
    }
}

Call invalidate() immediately on sign-out or account change, even when no replacement request starts; cancel the old task at that boundary too. Cancel superseded tasks on reload. There is no suspension between the ownership check and state assignment. Guard loading and pagination state too. This recipe implements latest-invocation-wins for one screen; independent requests need separate ownership slots.

3. Restore credentials before the first authenticated fetch

Keep persistent credential storage separate from the ephemeral network session. Use a generic-password Keychain item identified by a stable kSecAttrService and the selected account's kSecAttrAccount; reuse the same identity for add, lookup and update. Apple's adding guide introduces password items; the generic-password reference lists their identity attributes.

  • Save credential bytes with SecItemAdd; on errSecDuplicateItem, update that same item's kSecValueData with SecItemUpdate. Surface other statuses. Updating items.
  • Restore with SecItemCopyMatching, kSecReturnData: true and kSecMatchLimitOne. Handle errSecItemNotFound separately from other statuses; surface access failures. Searching items.
  • Choose accessibility for the actual execution requirement. An unlocked-only item cannot satisfy a locked-device refresh; choose an appropriate class deliberately. Apple's accessibility classes.

Recommended ordering: finish credential replacement and account selection before issuing requests; invalidate older UI requests at the same boundary.

Diagnostic: fixture execution stops at a precondition

A failed fixture expectation should become a normal XCTest failure or a thrown setup error. Do not turn an HTTP error, missing credential or malformed response into a process-ending invariant. Swift's precondition) stops execution on failure in ordinary Debug and Release optimization modes; its condition is omitted under -Ounchecked.

Evidence and limits

  • Apple, June 2021: Protect mutable state with Swift actors establishes reentrancy and checking state after suspension.
  • fawad-khalil-retailo, September 8, 2022: React Native issue #34627 reports iOS redirect header loss: “Authorization header dropped”. This is a firsthand report from another iOS client, not evidence that every native Swift/OS combination behaves identically.

Exercise real redirect hops on the target OS; request mocks cannot establish transport forwarding. Credential refresh, server authorization and background transfers require additional policies.

Started from a post by @Apple, packaged by the editor. Original post

Subjects

More in agent workflows

For agents

Copy a short instruction for an agent that has WhatWorks connected, or open this page as Markdown.

# SwiftUI: keep bearer redirects and responses in scope
Summary: Use a canonical API URL, allow bearer redirects only within an explicit HTTPS origin, reject obsolete UI responses and restore credentials through Keychain. Configure the foreground session with `URLSessionConfiguration.ephemeral`
Copy for agent
get the whatworks thread swiftui-urlsession-bearer-redirect-freshness-keychain and help me try it

Follow this thread

Following tells you when the verdict changes, a new version ships or a new option is added. Your agent mentions it the next time you ask WhatWorks.

Sign in with GitHub to follow. Nothing is posted for you.

Sign in with GitHub

Or ask your agent
follow the whatworks thread swiftui-urlsession-bearer-redirect-freshness-keychain
WhatWorks

Connect your agent MCP

Paste this into your agent

Connect me to WhatWorks: add https://whatworks.dev/mcp/login and sign me in so I have an account. Steps: https://whatworks.dev/connect.md.

Or run this in your terminal
  • Claude Codeclaude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp/login && claude mcp login whatworks
  • Codexcodex mcp add whatworks --url https://whatworks.dev/mcp/login && codex mcp login whatworks