---
title: "Secure Dart Frog APIs with API Key Authentication"
description: "Secure your Dart Frog API using a shared secret."
canonicalUrl: "https://zuplo.com/use-cases/api-key-auth/dart/dartfrog/secure-header"
framework: "Dart Frog"
language: "Dart"
authStrategy: "shared secret header"
pageType: use-case
---

# Secure Dart Frog APIs with API Key Authentication

Secure your Dart Frog API using a shared secret.

## How Zuplo Handles It

Put Zuplo in front of your Dart Frog backend to authenticate API keys and forward a shared secret header so your origin only accepts traffic from Zuplo.

## Dart Frog Backend Code

```dart
import 'dart:convert';
import 'dart:io';
import 'package:dart_frog/dart_frog.dart';

// Middleware to validate shared secret header
Handler validateSharedSecret(Handler handler) {
  return (context) async {
    final secret = context.request.headers['x-shared-secret'];
    final expectedSecret = Platform.environment['SHARED_SECRET'];

    if (expectedSecret == null) {
      return Response.json(
        statusCode: HttpStatus.internalServerError,
        body: {'error': 'Server configuration error'},
      );
    }

    if (secret == null) {
      return Response.json(
        statusCode: HttpStatus.unauthorized,
        body: {'error': 'No secret provided'},
      );
    }

    // Use constant-time comparison to prevent timing attacks
    if (!_secureCompare(secret, expectedSecret)) {
      return Response.json(
        statusCode: HttpStatus.unauthorized,
        body: {'error': 'Invalid secret'},
      );
    }

    return handler(context);
  };
}

bool _secureCompare(String a, String b) {
  if (a.length != b.length) return false;
  var isEqual = true;
  for (var i = 0; i < a.length; i++) {
    isEqual &= a.codeUnitAt(i) == b.codeUnitAt(i);
  }
  return isEqual;
}

// Example usage
Handler middleware(Handler handler) {
  return validateSharedSecret(handler);
}

Handler onRequest(RequestContext context) {
  return Response.json(body: {'message': 'Access granted'});
}
```

## Example Request

```bash
curl -X GET \
  'https://your-api.zuplo.dev/your-route' \
  -H 'Authorization: Bearer YOUR_API_KEY'
```

## Learn More

- [API Key Authentication on Zuplo](https://zuplo.com/docs/policies/api-key-auth-inbound)
- [JWT Authentication on Zuplo](https://zuplo.com/docs/policies/open-id-jwt-auth-inbound)
- [All use cases](https://zuplo.com/use-cases)
