---
title: "Secure Django REST Framework APIs with API Key Authentication"
description: "Secure your Django REST Framework API using a shared secret."
canonicalUrl: "https://zuplo.com/use-cases/api-key-auth/python/djangorestframework/secure-header"
framework: "Django REST Framework"
language: "Python"
authStrategy: "shared secret header"
pageType: use-case
---

# Secure Django REST Framework APIs with API Key Authentication

Secure your Django REST Framework API using a shared secret.

## How Zuplo Handles It

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

## Django REST Framework Backend Code

```python
import os
import hmac
import hashlib
from django.http import JsonResponse
from rest_framework.views import APIView
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from rest_framework.permissions import BasePermission

class SharedSecretPermission(BasePermission):
    def has_permission(self, request, view):
        secret_header = request.headers.get("X-Shared-Secret")
        expected_secret = os.environ.get("SHARED_SECRET")

        if not expected_secret:
            return JsonResponse({'error': 'Server configuration error'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        if not secret_header:
            return False

        # Use HMAC to ensure timing-safe comparison
        if not hmac.compare_digest(secret_header, expected_secret):
            return False

        return True

class ProtectedView(APIView):
    permission_classes = [SharedSecretPermission]

    def get(self, request):
        return Response({"message": "Access granted"}, status=status.HTTP_200_OK)

# Add this path to your urls.py
# path('protected/', ProtectedView.as_view(), name='protected')
```

## 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)
