florimondmanca / djangorestframework-api-key

🔐 API key permissions for Django REST Framework
https://florimondmanca.github.io/djangorestframework-api-key/
MIT License
678 stars 104 forks source link

Customizing Api-Key name (documentation incorrect) #258

Open AxisNL opened 1 year ago

AxisNL commented 1 year ago

Hi,

I have a requirement to change the Api-Key name, but I can't get it to work. I'm not that great of a developer ;)

Running djangorestframework-api-key 2.3.0 for a new project, and getting started with Api keys. I have to support a remote client that needs to send me a header in the format "Authorization: API-KEY ", so I need to change Api-Key to API-KEY.

The documentation however, doesn't seem to work:

from rest_framework_api_key.models import HasAPIKey
from rest_framework_api_key.permissions import BaseHasAPIKey, KeyParser

class BearerKeyParser(KeyParser):
    keyword = "Bearer"

class HasAPIKey(BaseHasAPIKey):
    model = APIKey  # Or a custom model
    key_parser = BearerKeyParser()

As rest_framework_api_key.models does not have a HasAPIKey class for example.

I assume it has to be something like this:

from rest_framework_api_key.models import APIKey
from rest_framework_api_key.permissions import BaseHasAPIKey, KeyParser

class BearerKeyParser(KeyParser):
    keyword = "API-KEY"

class HasAPIKey(BaseHasAPIKey):
    model = APIKey  # Or a custom model
    key_parser = BearerKeyParser()

But if I add the imports to settings.py, I get the error "django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.".

I guess I need a bit more handholding ;)

florimondmanca commented 1 year ago

Hey,

That's right, the code example in the docs is a little lacking.

This code definitely shouldn't be in settings.py.

The import change is correct.

What you should do is declare these classes in a permissions.py file of yours inside an app folder (eg an accounts app of that's what you have), and then use that HasAPIKey class of yours in the rest of your code.

Another semi-hacky way is to import KeyParser somewhere (settings.py might work) and set its keyword class attribute.

KeyParser.keyword = "API-KEY"

I reckon this task could be easier if we had a setting similar to API_KEY_CUSTOM_HEADER, but for the keyword.

Hope this helps!

If you're up to help fixing the docs in a way that works for you, that would be much appreciated.