Claude
Skills
Sign in
Back

device-integrity

Included with Lifetime
$97 forever

Verify device legitimacy and app integrity using DeviceCheck (DCDevice per-device bits) and App Attest (DCAppAttestService key generation, attestation, and assertion flows). Use when implementing fraud prevention, detecting compromised devices, validating app authenticity with Apple's servers, protecting sensitive API endpoints with attested requests, or adding device verification to a backend architecture.

Backend & APIs

What this skill does


# 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)](#dcdevice-devicecheck-tokens)
- [DCAppAttestService (App Attest)](#dcappattestservice-app-attest)
- [App Attest Key Generation](#app-attest-key-generation)
- [App Attest Attestation Flow](#app-attest-attestation-flow)
- [App Attest Assertion Flow](#app-attest-assertion-flow)
- [Server Verification Guidance](#server-verification-guidance)
- [Error Handling](#error-handling)
- [Common Patterns](#common-patterns)
- [Common Mistakes](#common-mistakes)
- [Review Checklist](#review-checklist)
- [References](#references)

## DCDevice (DeviceCheck Tokens)

[`DCDevice`](https://sosumi.ai/documentation/devicecheck/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

```swift
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

```swift
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`](https://sosumi.ai/documentation/devicecheck/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

```swift
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.

```swift
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

```swift
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

Related in Backend & APIs