
Device Integrity
- 2.6k installs
- 944 repo stars
- Updated July 15, 2026
- dpearson2699/swift-ios-skills
device-integrity is an iOS skill for DeviceCheck tokens and App Attest attestation or assertion based device verification.
About
The device-integrity skill covers Apple DeviceCheck and App Attest for fraud prevention and app authenticity on iOS. DCDevice generates single-use tokens for server calls to Apple query_two_bits, update_two_bits, or validate_device_token endpoints using a DeviceCheck JWT from the developer portal. Two per-device bits persist across reinstalls for flags like promo claims or fraud markers. DCAppAttestService on iOS 14 plus uses Secure Enclave keys with attestation once per key and assertions on ongoing requests; simulators and unsupported extensions must fall back. Guidance stresses one key per user account per device, storing keyId in Keychain, never reusing tokens, and discarding keyIds when server attestation verification fails. Server sections outline JWT auth to Apple, development versus production API hosts, and verifying attestation objects before trusting assertions. Common patterns combine DCDevice for lightweight checks with App Attest on high-value endpoints. Review checklist and error handling sections address unsupported devices, extension limits, and server verification failures.
- DCDevice tokens are single-use; generate a new token per server operation.
- App Attest uses generateKey, attestKey, and generateAssertion with server verification.
- Store one keyId per user account per device; avoid unnecessary key regeneration.
- DeviceCheck bits persist across reinstall; server sets meaning for two booleans.
- App Attest unsupported on simulators; check isSupported and extension type limits.
Device Integrity by the numbers
- 2,604 all-time installs (skills.sh)
- +114 installs in the week ending Jul 29, 2026 (Skillselion tracking)
- Ranked #191 of 2,203 Security skills by installs in the Skillselion catalog
- Security screen: MEDIUM risk (skills.sh audit)
- Data as of Jul 31, 2026 (Skillselion catalog sync)
device-integrity capabilities & compatibility
- Capabilities
- dcdevice token generation and server handoff pat · app attest key generation and keychain keyid per · attestation and assertion client flows with cryp · server verification and apple api endpoint overv · extension support limits and fallback guidance
- Use cases
- security audit · api development
- Platforms
- macOS
What device-integrity says it does
Treat each token as single-use: generate a new token for each server operation
Generate one cryptographic key pair per user account on each device.
App Attest is not available on simulators or all device models.
npx skills add https://github.com/dpearson2699/swift-ios-skills --skill device-integrityAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 2.6k |
|---|---|
| repo stars | ★ 944 |
| Security audit | 3 / 3 scanners passed |
| Last updated | July 15, 2026 |
| Repository | dpearson2699/swift-ios-skills ↗ |
How do I verify requests come from a genuine Apple device running a legitimate copy of my app?
Implement DeviceCheck tokens and App Attest attestation or assertion flows to verify genuine devices and legitimate app instances on sensitive APIs.
Who is it for?
iOS apps protecting promos, accounts, or APIs with Apple device integrity APIs.
Skip if: Skip for Android attestation or server-only auth without Apple DeviceCheck or App Attest.
When should I use this skill?
User mentions DeviceCheck, App Attest, DCAppAttestService, fraud prevention, or device tokens.
What you get
Working DCDevice token or App Attest flows with server-side Apple verification and key lifecycle discipline.
- Attestation verification checklist
- Server verifier implementation guidance
Files
Device Integrity
Verify that requests to your server come from a genuine Apple device running a legitimate instance of your app. DeviceCheck provides per-device bits for simple flags (e.g., "claimed promo offer"). App Attest uses Secure Enclave keys and Apple attestation to cryptographically prove app legitimacy on sensitive requests.
Contents
- DCDevice (DeviceCheck Tokens)
- DCAppAttestService (App Attest)
- App Attest Key Generation
- App Attest Attestation Flow
- App Attest Assertion Flow
- Server Verification Guidance
- Error Handling
- Common Patterns
- Common Mistakes
- Review Checklist
- References
DCDevice (DeviceCheck Tokens)
`DCDevice` generates a unique, ephemeral token that identifies a device. Treat each token as single-use: generate a new token for each server operation instead of caching or reusing one. The token is sent to your server, which then communicates with Apple's servers to read or set two per-device bits. Available on iOS 11+.
Token Generation
import DeviceCheck
func generateDeviceToken() async throws -> Data {
guard DCDevice.current.isSupported else {
throw DeviceIntegrityError.deviceCheckUnsupported
}
return try await DCDevice.current.generateToken()
}Sending the Token to Your Server
func sendTokenToServer(_ token: Data) async throws {
let tokenString = token.base64EncodedString()
var request = URLRequest(url: serverURL.appending(path: "verify-device"))
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try JSONEncoder().encode(["device_token": tokenString])
let (_, response) = try await URLSession.shared.data(for: request)
guard let httpResponse = response as? HTTPURLResponse,
httpResponse.statusCode == 200 else {
throw DeviceIntegrityError.serverVerificationFailed
}
}Server-Side Overview
Your server uses the device token to call Apple's DeviceCheck API endpoints:
| Endpoint | Purpose |
|---|---|
https://api.devicecheck.apple.com/v1/query_two_bits | Read the two bits for a device |
https://api.devicecheck.apple.com/v1/update_two_bits | Set the two bits for a device |
https://api.devicecheck.apple.com/v1/validate_device_token | Validate a device token without reading bits |
The server authenticates with a DeviceCheck private key from the Apple Developer portal, creating a signed JWT for each request.
Use https://api.development.devicecheck.apple.com only while testing; use https://api.devicecheck.apple.com for production.
What the Two Bits Are For
Apple stores two Boolean values per device per developer team. You decide what they mean. Common uses:
- Bit 0: Device has claimed a promotional offer.
- Bit 1: Device has been flagged for fraud.
Bits persist across app reinstall. You control when to reset them via the server API.
DCAppAttestService (App Attest)
`DCAppAttestService` validates that a specific instance of your app on a specific device is legitimate. It uses a hardware-backed key in the Secure Enclave to create cryptographic attestations and assertions. Available on iOS 14+.
The flow has three phases: 1. Key generation -- create a key pair in the Secure Enclave. 2. Attestation -- Apple certifies the key belongs to a genuine Apple device running your app. 3. Assertion -- sign server requests with the attested key to prove ongoing legitimacy.
Checking Support
import DeviceCheck
let attestService = DCAppAttestService.shared
guard attestService.isSupported else {
// Fall back to DCDevice token or other risk assessment.
// App Attest is not available on simulators or all device models.
return
}For app extensions, App Attest is supported only in Action, extensible SSO, and watchOS extensions. Treat other extension types as unsupported even if isSupported returns true.
App Attest Key Generation
Generate one cryptographic key pair per user account on each device. The private key stays in the Secure Enclave. The returned keyId is the only identifier your app can later use to access the key, so record and reuse the account/device-scoped keyId; do not share one key across users. Avoid unnecessary regeneration because each new key affects App Attest key-count risk metrics. Only treat the keyId as usable after your server verifies attestation. If server verification fails, discard the keyId and generate a new key before retrying.
import DeviceCheck
actor AppAttestManager {
private let service = DCAppAttestService.shared
private var keyId: String?
/// Generate and record a key pair for App Attest.
func generateKeyIfNeeded() async throws -> String {
if let existingKeyId = loadKeyIdFromKeychain() {
self.keyId = existingKeyId
return existingKeyId
}
let newKeyId = try await service.generateKey()
saveKeyIdToKeychain(newKeyId)
self.keyId = newKeyId
return newKeyId
}
// MARK: - Keychain helpers (simplified)
private func saveKeyIdToKeychain(_ keyId: String) {
let data = Data(keyId.utf8)
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: "app-attest-key-id-\(currentAccountID)",
kSecAttrService as String: Bundle.main.bundleIdentifier ?? "",
kSecValueData as String: data,
kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
]
SecItemDelete(query as CFDictionary) // Remove old if exists
SecItemAdd(query as CFDictionary, nil)
}
private func loadKeyIdFromKeychain() -> String? {
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: "app-attest-key-id-\(currentAccountID)",
kSecAttrService as String: Bundle.main.bundleIdentifier ?? "",
kSecReturnData as String: true,
kSecMatchLimit as String: kSecMatchLimitOne
]
var result: AnyObject?
let status = SecItemCopyMatching(query as CFDictionary, &result)
guard status == errSecSuccess, let data = result as? Data else { return nil }
return String(data: data, encoding: .utf8)
}
}Important: Generate the key once per user account on a device, persist that account/device keyId, and keep the key count low. Generating unnecessary keys pollutes App Attest risk metrics.
App Attest Attestation Flow
Attestation proves that the key was generated on a genuine Apple device running a legitimate instance of your app. You perform attestation once per key, then store the verified public key and receipt on your server. The app stores the keyId for future assertions after the server accepts the attestation.
Client-Side Attestation
import DeviceCheck
import CryptoKit
extension AppAttestManager {
/// Attest the key with Apple. Send the attestation object to your server.
func attestKey() async throws -> Data {
guard let keyId else {
throw DeviceIntegrityError.keyNotGenerated
}
// 1. Request a one-time challenge from your server
let challenge = try await fetchServerChallenge()
// 2. Hash the challenge (Apple requires a SHA-256 hash)
let challengeHash = Data(SHA256.hash(data: challenge))
// 3. Ask Apple to attest the key
let attestation = try await service.attestKey(keyId, clientDataHash: challengeHash)
// 4. Send the attestation object to your server for verification
try await sendAttestationToServer(
keyId: keyId,
attestation: attestation,
challenge: challenge
)
return attestation
}
private func fetchServerChallenge() async throws -> Data {
let url = serverURL.appending(path: "attest/challenge")
let (data, _) = try await URLSession.shared.data(from: url)
return data
}
private func sendAttestationToServer(
keyId: String,
attestation: Data,
challenge: Data
) async throws {
var request = URLRequest(url: serverURL.appending(path: "attest/verify"))
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let payload: [String: String] = [
"key_id": keyId,
"attestation": attestation.base64EncodedString(),
"challenge": challenge.base64EncodedString()
]
request.httpBody = try JSONEncoder().encode(payload)
let (_, response) = try await URLSession.shared.data(for: request)
guard let httpResponse = response as? HTTPURLResponse,
httpResponse.statusCode == 200 else {
throw DeviceIntegrityError.attestationVerificationFailed
}
}
}Server-Side Attestation Verification
Your server validates the attestation object (CBOR), verifies the certificate chain against Apple's App Attest root CA, checks Apple's nonce calculation, and stores the verified public key and receipt for future assertion verification. The attestation nonce is not SHA256(challenge) alone; it is SHA256(authData || SHA256(challenge)) and is compared with the credential certificate extension 1.2.840.113635.100.8.2. See references/device-integrity-patterns.md for the full server verification flow.
App Attest Assertion Flow
After attestation, use assertions to sign sensitive requests. Each assertion proves the request came from the attested app instance and includes a server-issued, one-time challenge to prevent replay.
Client-Side Assertion
import DeviceCheck
import CryptoKit
extension AppAttestManager {
/// Generate an assertion for encoded client data.
/// Client data should include a one-time server challenge and request context.
func generateAssertion(for clientData: Data) async throws -> Data {
guard let keyId else {
throw DeviceIntegrityError.keyNotGenerated
}
let clientDataHash = Data(SHA256.hash(data: clientData))
return try await service.generateAssertion(keyId, clientDataHash: clientDataHash)
}
}Using Assertions in Network Requests
struct AppAttestClientData: Encodable {
let challenge: String
let method: String
let path: String
let bodySHA256: String
}
extension AppAttestManager {
/// Perform an attested API request.
func makeAttestedRequest(
to url: URL,
method: String = "POST",
body: Data
) async throws -> (Data, URLResponse) {
let challenge = try await fetchAssertionChallenge()
let bodyHash = Data(SHA256.hash(data: body)).base64EncodedString()
let clientData = try JSONEncoder().encode(
AppAttestClientData(
challenge: challenge,
method: method,
path: url.path,
bodySHA256: bodyHash
)
)
let assertion = try await generateAssertion(for: clientData)
var request = URLRequest(url: url)
request.httpMethod = method
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue(assertion.base64EncodedString(), forHTTPHeaderField: "X-App-Attest-Assertion")
request.setValue(clientData.base64EncodedString(), forHTTPHeaderField: "X-App-Attest-Client-Data")
request.httpBody = body
return try await URLSession.shared.data(for: request)
}
private func fetchAssertionChallenge() async throws -> String {
let url = serverURL.appending(path: "assert/challenge")
let (data, _) = try await URLSession.shared.data(from: url)
return String(decoding: data, as: UTF8.self)
}
}Server-Side Assertion Verification
Your server decodes the assertion (CBOR), verifies the authenticator data and counter, recomputes clientDataHash from the submitted client data, verifies the signature over SHA256(authenticatorData || clientDataHash) with the stored public key, and confirms the embedded challenge and request context. See references/device-integrity-patterns.md for step-by-step server verification.
Server Verification Guidance
See references/device-integrity-patterns.md for full server architecture guidance including attestation vs. assertion comparison, recommended endpoint design, and risk assessment.
Security Boundaries
App Attest proves app-instance integrity for selected requests. It does not replace user authentication, OAuth/JWT/session handling, API token design, entitlement or subscription authorization, TLS, certificate pinning, or general networking security. Treat those as handoffs to authentication, networking, or broader security guidance, and still enforce normal authentication and authorization after App Attest passes.
Error Handling
Handle DCError codes from DeviceCheck operations. Key cases:
.serverUnavailable— retry with exponential backoff.invalidKey— the key was already attested, assertion used an unattested key, or the service rejected the key.featureUnsupported— fall back toDCDevicetokens.invalidInput— malformedclientDataHashorkeyId
For attestKey, retry .serverUnavailable later with the same keyId and the same clientDataHash. For other attestation errors, discard the key identifier and create a new key before retrying. See references/device-integrity-patterns.md for full error handling code, retry strategy, and rejected-key recovery.
Common Patterns
Environment Entitlement
Set the App Attest environment in your entitlements file. Use development during testing and production for App Store builds:
<key>com.apple.developer.devicecheck.appattest-environment</key>
<string>production</string>When the entitlement is omitted during development, the app uses the App Attest sandbox by default. After distribution through TestFlight, the App Store, or the Apple Developer Enterprise Program, the app ignores the entitlement value and uses production.
See references/device-integrity-patterns.md for the full integration manager pattern, gradual rollout guidance, and error type definition.
Common Mistakes
1. Generating a new key on every launch. Generate once per user account on a device, persist the keyId, and keep key counts low. 2. Reusing `DCDevice` tokens. Treat generated tokens as single-use. Generate a new token for each server operation. 3. Skipping the fallback for unsupported devices or extensions. Not all devices and extension types support App Attest. Use DCDevice tokens or other risk assessment as fallback. 4. Trusting attestation client-side. All verification must happen on your server. 5. Signing only the raw request body. Assertion client data must include a one-time server challenge and enough request context for the server to bind the assertion to the request. 6. Verifying the wrong attestation nonce. Compare the certificate extension with SHA256(authData || SHA256(challenge)), not SHA256(challenge) alone. 7. Not implementing replay protection. The server must validate one-time challenges and track the assertion counter. 8. Mixing development and production environments. Sandbox keys and receipts do not work in production, and production keys and receipts do not work in sandbox. 9. Not handling `DCError.invalidKey`. Check for repeated attestation, unattested assertion keys, or service rejection; regenerate only after the state is known bad.
Review Checklist
- [ ]
DCDevicetokens generated per server operation and never cached for reuse - [ ]
DCAppAttestService.isSupportedchecked before use; unsupported devices and extension types have a fallback - [ ] Key generated once per user account on each device and
keyIdpersisted only for that app account/device - [ ] Attestation performed once per key; server stores verified public key and receipt
- [ ] Server validates attestation certificate chain, App ID hash, environment
aaguid, credential ID, and nonceSHA256(authData || SHA256(challenge)) - [ ] Assertions include one-time challenge plus request context; server verifies signature, RP ID, counter, challenge, and request binding
- [ ] Protected endpoints still enforce normal user authentication and entitlement authorization after App Attest passes
- [ ]
DCErrorcases handled:.serverUnavailableretries attestation with the same key/hash; bad keys are discarded and regenerated - [ ] App Attest environment entitlement and sandbox/production server routing are consistent
- [ ] Gradual rollout considered; feature flag in place for enabling/disabling
References
- Extended patterns: references/device-integrity-patterns.md
- DeviceCheck framework
- DCDevice
- DCAppAttestService
- Establishing your app's integrity
- Validating apps that connect to your server
- Attestation Object Validation Guide
- App Attest Environment
{
"skill_name": "device-integrity",
"evals": [
{
"id": 0,
"name": "app-attest-attestation-verifier",
"prompt": "We're adding server-side App Attest verification for an iOS app. The client sends keyId, attestationObject, and the original one-time challenge. What exact checks should the verifier perform before storing anything?",
"expected_output": "A source-grounded App Attest attestation verification checklist that covers CBOR/certificate validation, nonce composition, App ID and environment checks, credential ID/keyId checks, and storing verified public key plus receipt.",
"files": [],
"expectations": [
"Computes `clientDataHash = SHA256(challenge)`, then verifies the certificate nonce against `SHA256(authData || clientDataHash)` rather than `SHA256(challenge)` alone.",
"Names the credential certificate extension OID `1.2.840.113635.100.8.2` as the source of the nonce value to compare.",
"Verifies the App ID/RP ID hash, environment `aaguid`, initial counter, `credentialId`, and keyId/public-key hash relationship.",
"Stores the verified public key and receipt for future assertion and fraud-risk use instead of treating the raw attestation object as the trusted durable record."
]
},
{
"id": 1,
"name": "app-attest-sensitive-request-assertion",
"prompt": "Design the App Attest assertion contract for a premium-content download endpoint. The app already has an attested key. What should the client sign and what should the server verify on every sensitive request?",
"expected_output": "A replay-safe assertion design that signs client data containing a server challenge and request context, then verifies assertion CBOR, signature, RP ID, counter, challenge, and request binding server-side.",
"files": [],
"expectations": [
"Requires a fresh one-time server challenge for the assertion flow and embeds it in the client data.",
"Includes request context or a request-body hash in the signed client data so the assertion is bound to the sensitive request.",
"Verifies the assertion signature over `SHA256(authenticatorData || SHA256(clientData))` using the public key stored from attestation.",
"Checks the RP ID hash, monotonically increasing counter, and embedded challenge before accepting the request."
]
},
{
"id": 2,
"name": "device-integrity-boundary-and-errors",
"prompt": "Review this plan: cache a DCDevice token for the whole install, use one App Attest key for all users, retry any attestKey failure with a new key immediately, treat invalidKey as an OS update problem, and add OAuth/session-token/certificate-pinning advice to the same device-integrity checklist. What should be corrected?",
"expected_output": "A boundary-aware correction list that fixes DeviceCheck token reuse, App Attest key scope, retry/error handling, environment behavior, and routes unrelated authentication/network security work to sibling guidance.",
"files": [],
"expectations": [
"States that `DCDevice.generateToken()` tokens are single-use and should not be cached for the whole install.",
"Requires App Attest keys to be unique per user account on each device and warns against unnecessary key generation because it affects risk metrics.",
"For `serverUnavailable`, retries attestation later with the same key and same `clientDataHash`; for other attestation errors, discards the key identifier before a new-key retry.",
"Describes `invalidKey` using Apple-documented causes: already-attested key, unattested assertion key, or service rejection, without attributing it to OS updates or Secure Enclave resets.",
"Keeps OAuth/session-token design, certificate pinning, and broad networking security out of the device-integrity checklist except as sibling-skill handoffs."
]
}
]
}
Device Integrity Extended Patterns
Overflow reference for the device-integrity skill. Contains server verification details, advanced error handling, and integration patterns.
Contents
- Server-Side Attestation Verification
- Server-Side Assertion Verification
- Server Architecture
- Error Handling
- Retry Strategy
- Handling Rejected Keys
- Full Integration Manager
- Gradual Rollout
- Environment Entitlement
Server-Side Attestation Verification
Your server must: 1. Verify the attestation object is a valid CBOR-encoded structure. 2. Extract the certificate chain and validate it against Apple's App Attest root CA. 3. Compute clientDataHash = SHA256(challenge), append it to the decoded authData, then compute nonce = SHA256(authData || clientDataHash). 4. Extract the credential certificate extension with OID 1.2.840.113635.100.8.2 and verify its octet string equals nonce. 5. Verify the public-key hash matches the app-provided keyId. 6. Verify the RP ID hash matches SHA256(teamID + "." + bundleID). 7. Verify the initial counter is 0, the aaguid matches the expected development or production environment, and credentialId equals keyId. 8. Store the verified public key and receipt for future assertion verification. 9. Mark the challenge consumed only after every verification step succeeds, ideally in the same transaction that stores the key state.
See Validating apps that connect to your server for the full server verification algorithm.
Server-Side Assertion Verification
Your server must: 1. Decode the assertion (CBOR). 2. Recompute clientDataHash = SHA256(clientData), where clientData includes a one-time server challenge and request context. 3. Verify the signature using the stored public key over SHA256(authenticatorData || clientDataHash). 4. Verify the RP ID hash and the counter (greater than the stored counter, or greater than 0 for the first assertion). 5. Confirm the embedded challenge matches the issued challenge and the request context binds the assertion to the received request. 6. Mark the challenge consumed and update the stored counter only after every verification step succeeds, ideally atomically.
Server Architecture
Attestation vs. Assertion
| Phase | When | What It Proves | Frequency |
|---|---|---|---|
| Attestation | After key generation | The key lives on a genuine Apple device running a legitimate instance of your app | Once per key |
| Assertion | With each sensitive request | The request came from the attested app instance | Per request |
Recommended Server Architecture
1. Challenge endpoint -- generate a random nonce with at least 16 bytes of entropy, store it server-side with a short TTL (e.g., 5 minutes), purpose, and expected request/key context. 2. Attestation verification endpoint -- validate the attestation object, store the public key and receipt keyed by keyId. 3. Assertion verification middleware -- verify assertions on sensitive endpoints (purchases, account changes).
Reject expired, missing, mismatched, or already-consumed challenges. Consume a challenge only after the corresponding attestation or assertion is fully verified; consuming on receipt can block safe retries after transient failures.
Risk Assessment
Combine App Attest with fraud risk assessment for defense in depth. App Attest alone does not guarantee the user is not abusing the app -- it confirms the app is genuine.
App Attest is not a user authentication, session, entitlement, TLS, certificate pinning, or subscription validation system. Keep those controls in the appropriate authentication, networking, or broader security layer, and require them in addition to App Attest on protected endpoints.
Error Handling
DCError Codes
import DeviceCheck
func handleAttestError(_ error: Error) {
if let dcError = error as? DCError {
switch dcError.code {
case .unknownSystemFailure:
// Transient system error -- retry with exponential backoff
break
case .featureUnsupported:
// Device or OS does not support this feature
// Fall back to alternative verification
break
case .invalidKey:
// Already-attested key, unattested assertion key, or service rejection
// Inspect local/server state; discard and regenerate only when bad
break
case .invalidInput:
// The clientDataHash or keyId was malformed
break
case .serverUnavailable:
// Retry attestation later with the same keyId and clientDataHash
break
@unknown default:
break
}
}
}Retry Strategy
import CryptoKit
extension AppAttestManager {
func attestKeyWithRetry(challenge: Data, maxAttempts: Int = 3) async throws -> Data {
guard let keyId else {
throw DeviceIntegrityError.keyNotGenerated
}
let clientDataHash = Data(SHA256.hash(data: challenge))
var lastError: Error?
for attempt in 0..<maxAttempts {
do {
return try await service.attestKey(keyId, clientDataHash: clientDataHash)
} catch let error as DCError where error.code == .serverUnavailable {
lastError = error
if attempt < maxAttempts - 1 {
try await Task.sleep(for: .seconds(pow(2.0, Double(attempt + 1))))
}
} catch {
throw error // Non-retryable errors propagate immediately
}
}
throw lastError ?? DeviceIntegrityError.attestationFailed
}
}Use the same challenge, keyId, and clientDataHash for each retry after .serverUnavailable. Do not fetch a fresh challenge for that retry loop unless you are also starting over with a new attestation attempt.
Handling Rejected Keys
DCError.invalidKey means the app called attestKey for an already-attested key, called generateAssertion with an unattested key, or the App Attest service rejected the key. If local/server state confirms the key cannot be used, delete the stored keyId and generate a new key:
extension AppAttestManager {
func handleRejectedKey() async throws -> String {
deleteKeyIdFromKeychain()
keyId = nil
return try await generateKeyIfNeeded()
}
private func deleteKeyIdFromKeychain() {
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: "app-attest-key-id",
kSecAttrService as String: Bundle.main.bundleIdentifier ?? ""
]
SecItemDelete(query as CFDictionary)
}
}Full Integration Manager
Combine the patterns above into a single actor that manages the full lifecycle: 1. Check isSupported and fall back to DCDevice tokens on unsupported devices. 2. Call generateKeyIfNeeded() for each user account on each device, reuse the account/device-scoped keyId, and limit new key generation to new account/device/install enrollment or confirmed bad-key recovery. 3. Attest once per key; if .serverUnavailable occurs, retry with the same challenge, key, and clientDataHash. 4. For each sensitive request, obtain a one-time assertion challenge and sign client data that includes the challenge plus request context. 5. Handle DCError.invalidKey by checking whether the key was already attested, not yet attested, or rejected before regenerating.
Gradual Rollout
Apple recommends a gradual rollout. Gate App Attest behind a remote feature flag and fall back to DCDevice tokens on unsupported devices. For large apps, ramp production adoption gradually and be prepared to reduce attestation traffic if .serverUnavailable or rate-limit behavior increases during rollout.
Environment Entitlement
Set the App Attest environment in your entitlements file. Use development during testing and production for App Store builds:
<key>com.apple.developer.devicecheck.appattest-environment</key>
<string>production</string>When the entitlement is omitted during development, the app uses the App Attest sandbox by default. After distribution through TestFlight, the App Store, or the Apple Developer Enterprise Program, the app ignores the entitlement value and uses production. Sandbox keys and receipts do not work in production, and production keys and receipts do not work in sandbox.
If an App Clip or extension uses App Attest, configure the capability for that target too. App Attest is supported only in Action, extensible SSO, and watchOS extensions; other extension types are unsupported even if isSupported returns true.
Error Type
enum DeviceIntegrityError: Error {
case deviceCheckUnsupported
case keyNotGenerated
case attestationFailed
case attestationVerificationFailed
case assertionFailed
case serverVerificationFailed
}Apple Documentation Links
Related skills
How it compares
Use device-integrity for Apple-native attestation flows; pick generic API auth skills when device cryptographic proof is not required.
FAQ
When should I use DeviceCheck versus App Attest?
DeviceCheck suits simple per-device flags; App Attest cryptographically proves app legitimacy on sensitive requests.
Can App Attest run in the simulator?
No. Fall back to DCDevice or other risk checks when isSupported is false.
How many App Attest keys should I create?
One key per user account per device; persist keyId and avoid unnecessary regeneration.
Is Device Integrity safe to install?
skills.sh reports 3 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.