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; onerrSecDuplicateItem, update that same item'skSecValueDatawithSecItemUpdate. Surface other statuses. Updating items. - Restore with
SecItemCopyMatching,kSecReturnData: trueandkSecMatchLimitOne. HandleerrSecItemNotFoundseparately 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