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

# Secure Shelf APIs with API Key Authentication

Secure your Shelf API using a shared secret.

## How Zuplo Handles It

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

## Shelf Backend Code

```dart
import 'dart:io';
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as io;
import 'package:crypto/crypto.dart';

Middleware validateSharedSecret() {
  return (Handler innerHandler) {
    return (Request request) async {
      final secret = request.headers['x-shared-secret'];
      final expectedSecret = Platform.environment['SHARED_SECRET'];

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

      if (secret == null) {
        return Response(401, body: 'No secret provided');
      }

      final secretBytes = utf8.encode(secret);
      final expectedSecretBytes = utf8.encode(expectedSecret);

      if (!const ListEquality<int>().equals(secretBytes, expectedSecretBytes)) {
        return Response(401, body: 'Invalid secret');
      }

      return innerHandler(request);
    };
  };
}

void main() {
  final handler = const Pipeline()
      .addMiddleware(validateSharedSecret())
      .addHandler(_echoRequest);

  io.serve(handler, 'localhost', 8080);
}

Response _echoRequest(Request request) =>
    Response.ok('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)
