Skip to content

Instantly share code, notes, and snippets.

@mehdi89
Created June 29, 2024 10:32
Show Gist options
  • Save mehdi89/bad63980ff72e6a66b4ec81a824661df to your computer and use it in GitHub Desktop.
Save mehdi89/bad63980ff72e6a66b4ec81a824661df to your computer and use it in GitHub Desktop.
ios app attestation.md

To implement and test App Attestation for iOS using DeviceCheck and a Next.js backend, you can follow these steps:

iOS Implementation

  1. Add DeviceCheck to your project:

    • Ensure your project has the DeviceCheck framework.
  2. Request DeviceCheck token:

    import DeviceCheck
    
    func requestDeviceCheckToken() {
        let deviceCheck = DCDevice.current
        if deviceCheck.isSupported {
            deviceCheck.generateToken(completionHandler: { (data, error) in
                if let error = error {
                    // Handle error
                    print("Error generating token: \(error)")
                    return
                }
                if let data = data {
                    let token = data.base64EncodedString()
                    sendToServer(token: token)
                }
            })
        } else {
            // DeviceCheck is not supported
            print("DeviceCheck not supported")
        }
    }
    
    func sendToServer(token: String) {
        // Implement network logic to send token to your server
    }

Next.js Backend Implementation

  1. Install required packages:

    npm install express body-parser axios
  2. Create API route for verification:

    // pages/api/verify.js
    import axios from 'axios';
    
    export default async function handler(req, res) {
      const { token } = req.body;
    
      if (!token) {
        return res.status(400).json({ success: false, error: "Missing token" });
      }
    
      try {
        const response = await axios.post('https://api.devicecheck.apple.com/v1/validate_device_token', {
          device_token: token
        }, {
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer YOUR_JWT_TOKEN`
          }
        });
    
        if (response.data.status === 'OK') {
          // Token is valid
          res.status(200).json({ success: true });
        } else {
          // Token is invalid
          res.status(403).json({ success: false });
        }
      } catch (error) {
        // Handle error
        res.status(500).json({ success: false, error: error.message });
      }
    }
  3. Setup your Next.js server:

    // server.js
    const express = require('express');
    const next = require('next');
    
    const dev = process.env.NODE_ENV !== 'production';
    const app = next({ dev });
    const handle = app.getRequestHandler();
    
    app.prepare().then(() => {
      const server = express();
      server.use(express.json());
    
      server.post('/api/verify', require('./pages/api/verify').default);
    
      server.all('*', (req, res) => {
        return handle(req, res);
      });
    
      server.listen(3000, (err) => {
        if (err) throw err;
        console.log('> Ready on http://localhost:3000');
      });
    });

Testing with Postman

  1. Set Up Postman:

    • Open Postman and create a new request.
    • Set the request type to POST.
    • Enter the endpoint URL (e.g., http://localhost:3000/api/verify).
  2. Prepare Mock DeviceCheck Token:

    • For testing, you can use a sample token or generate a mock token. Here's an example of a mock payload:
      {
        "token": "MOCK_DEVICE_CHECK_TOKEN"
      }
  3. Configure Postman Request:

    • Go to the Body tab and select raw.
    • Set the format to JSON.
    • Paste your mock token in the request body.
      {
        "token": "MOCK_DEVICE_CHECK_TOKEN"
      }
  4. Send Request and Analyze Response:

    • Click Send to send the request to your Next.js backend.
    • Check the response to ensure that your backend logic is working as expected.

Example Postman Request

Request Type: POST
URL: http://localhost:3000/api/verify

Headers:

Content-Type: application/json

Body (raw, JSON):

{
  "token": "MOCK_DEVICE_CHECK_TOKEN"
}

By following these steps, you can effectively test your backend API endpoints using Postman without needing the actual iOS client to send the requests. This allows you to ensure that your backend logic for verifying the DeviceCheck token is functioning correctly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment