Skip to content

API Keys in Public API

Implementing API Key Authentication in Django REST Framework for Public APIs"

When working with public APIs in Django REST Framework (DRF), using API keys for authentication is a common approach. Below is an example of how you can implement API key authentication in a DRF project.

Step 1: Install the Required Package

First, you need to install djangorestframework-api-key, which is a package specifically designed to handle API key authentication.

pip install djangorestframework-api-key

Step 2: Add rest_framework_api_key to Your INSTALLED_APPS

In your settings.py, add rest_framework_api_key to the INSTALLED_APPS list:

INSTALLED_APPS = [
    ...
    'rest_framework',
    'rest_framework_api_key',
]

Step 3: Create the API Key Model

Run migrations to create the database tables needed for API keys:

python manage.py migrate

Step 4: Set Up API Key Permissions

You can now create a view that requires an API key to access. Below is an example using the HasAPIKey permission class provided by djangorestframework-api-key.

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework_api_key.permissions import HasAPIKey
from rest_framework_api_key.models import APIKey

class PublicAPIView(APIView):
    permission_classes = [HasAPIKey]

    def get(self, request):
        data = {
            "message": "This is a public API that requires an API key."
        }
        return Response(data)

# To create an API key, you can do this in a Django shell:
# from rest_framework_api_key.models import APIKey
# api_key, key = APIKey.objects.create_key(name="my-api-key")
# print("API Key:", key)

Step 5: Use the API Key in Requests

When making a request to this API, you will need to include the API key in the Authorization header like this:

curl -H "Authorization: Api-Key your-api-key-here" https://your-domain.com/api/public/

Step 6: Customize API Key Management (Optional)

You can customize the behavior of API keys by overriding the default views or creating your own custom management commands.

This example shows the basics of using API keys in a public API in Django REST Framework. You can expand on this by adding expiration dates, scopes, or other custom behaviors to suit your needs.


To find or create API keys when using djangorestframework-api-key, follow these steps:

Creating API Keys

  1. Django Admin Interface:

    • Go to the Django admin interface (e.g., http://localhost:8000/admin).
    • Look for the API Keys section under the REST Framework API Key model.
    • Here, you can create a new API key by clicking the “Add API Key” button. You’ll be able to name the key and the system will generate a unique key value for you.
  2. Django Shell:

    • You can also create API keys using the Django shell. Open the Django shell with:

      python manage.py shell
      
    • Create an API key using the following code:

      from rest_framework_api_key.models import APIKey
      
      # Create a new API key
      api_key, key = APIKey.objects.create_key(name="my-api-key")
      print("API Key:", key)
      

Finding Existing API Keys

  1. Django Admin Interface:

    • In the Django admin interface, navigate to the API Keys section. You can view a list of all API keys here. The key values themselves are usually not shown for security reasons, but you can manage and revoke them from this interface.
  2. Django Shell:

    • You can retrieve existing API keys using the Django shell. For example:

      from rest_framework_api_key.models import APIKey
      
      # List all API keys
      keys = APIKey.objects.all()
      for key in keys:
          print(f"Name: {key.name}, Key: {key.key}")
      

    Note: Be cautious when printing or displaying API keys as they are sensitive information.

Important Security Note

Always keep your API keys secure and avoid exposing them publicly. Only share them with trusted parties and ensure they are transmitted securely (e.g., over HTTPS).


Rotate API Keys

To rotate API keys, you need to replace old keys with new ones while ensuring that your system remains functional and secure. Here’s a step-by-step guide on how to handle API key rotation in Django:

  1. Generate a New API Key

    You first need to generate a new API key. This can be done through the Django admin interface, Django shell, or programmatically via code.

    Django Admin Interface:
    • Go to the Django admin interface.
    • Navigate to the API Keys section.
    • Add a new API key by creating a new entry.
    Django Shell:
    from rest_framework_api_key.models import APIKey
    
    # Create a new API key
    api_key, new_key = APIKey.objects.create_key(name="new-api-key")
    print("New API Key:", new_key)
    

    Programmatically:

    You can also add code to your application that creates a new API key.

  2. Update Your Application to Use the New Key

    Once you have a new key, you need to update your application or any external services to use the new API key.

    • For Your Application: Update configuration files, environment variables, or any other places where the API key is used.
    • For External Services: If you have integrations or third-party services using the old key, update their configurations with the new key.
  3. Test the New Key

    Before revoking the old key, ensure that the new key works correctly. Test your application thoroughly to confirm that everything functions as expected with the new key.

  4. Revoke the Old API Key

    Once you have verified that the new key is working and all necessary updates have been made, you can revoke the old API key.

    Django Admin Interface:
    • Go to the API Keys section in the Django admin interface.
    • Find the old API key and delete it.
    from rest_framework_api_key.models import APIKey
    
    # Find and delete the old API key
    old_key = APIKey.objects.get(name="old-api-key")
    old_key.delete()
    
  5. Monitor and Validate

    After rotating the API key, monitor your application to ensure that there are no issues. Keep an eye on logs and error reports to catch any potential issues that might arise from the key rotation.

Automation and Best Practices
  • Automation: Consider automating API key rotation if possible, especially if you have multiple keys or high-security requirements. This can be done using scripts or integration with CI/CD pipelines.
  • Documentation: Keep documentation up to date with information on how API keys are rotated and managed.
  • Security: Regularly review your API key management practices to ensure they meet security standards.

By following these steps, you can effectively manage and rotate API keys in your Django application, helping to maintain security and minimize disruption.


How Often to Rotate API Keys

Rotation Frequency:
  • Security Policy: The frequency of API key rotation depends on your organization’s security policy and the sensitivity of the data or services the API key provides access to. Common practices are:

    • Quarterly: For high-security environments.
    • Annually: For lower-risk applications.
    • After Security Incidents: Immediately after a suspected breach or compromise.
  • Regulatory Requirements: Certain industries or regulatory standards may mandate specific key rotation schedules.


Automating API Key Rotation

Automating API key rotation involves setting up processes to generate, deploy, and revoke keys without manual intervention. Here’s a general approach to automate the process:

  1. Script for Key Management

    Create scripts to automate key creation, updating, and deletion. Below is an example of how you might script this in Python using Django’s ORM:

    # rotate_api_keys.py
    
    import os
    from django.core.management.base import BaseCommand
    from rest_framework_api_key.models import APIKey
    
    class Command(BaseCommand):
        help = 'Rotate API keys'
    
        def handle(self, *args, **kwargs):
            # Generate a new API key
            api_key, new_key = APIKey.objects.create_key(name="new-api-key")
            print(f"New API Key: {new_key}")
    
            # Revoke old API key (example, replace with actual logic)
            old_key_name = os.getenv('OLD_API_KEY_NAME', 'old-api-key')
            try:
                old_key = APIKey.objects.get(name=old_key_name)
                old_key.delete()
                print(f"Old API Key ({old_key_name}) revoked.")
            except APIKey.DoesNotExist:
                print(f"Old API Key ({old_key_name}) not found.")
    
  2. Update Configuration Automatically

    • Environment Variables: Update environment variables or configuration files that store the API key. This can be done by scripting or using a configuration management tool like Ansible, Chef, or Puppet.

    • Deployment Pipelines: Integrate the script into your CI/CD pipeline. For example, use Jenkins, GitLab CI, or GitHub Actions to trigger the script as part of your deployment process.

  3. Scheduled Rotation

    Use a scheduling tool to automate the key rotation script:

    • Cron Jobs: Set up a cron job on your server to run the script at regular intervals.

      # Open crontab
      crontab -e
      
      # Add a line to schedule the script
      0 0 1 * * /path/to/your/manage.py rotate_api_keys
      
    • Cloud Scheduler: If you’re using a cloud provider, you can use their scheduling services. For example, AWS Lambda with CloudWatch Events or Google Cloud Functions with Cloud Scheduler.

  4. Notify and Log

    • Notifications: Send notifications when keys are rotated to alert relevant teams. You can use email, Slack, or other communication tools.

    • Logging: Keep logs of key creation and deletion events for auditing and troubleshooting purposes.

  5. Testing and Validation

    • Test Automation: Implement automated tests to ensure that key rotation does not break your application. This includes integration tests that verify the application works with the new key.

    • Validation: Regularly validate your key rotation process to ensure it functions correctly and securely.

Summary

Automating API key rotation involves creating scripts for key management, integrating these scripts into your CI/CD pipelines, scheduling key rotation tasks, and ensuring proper notification and logging. The frequency of rotation depends on security needs and policy requirements. Regularly review and test your automation to maintain security and functionality.