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

Making invalid API Key raise 403 forbidden #262

Open Enorio opened 8 months ago

Enorio commented 8 months ago

I have a project that uses jwt tokens as authentication. I'm now trying to add the api-key feature. Basically I've customized the API based on an Organization permission (in a given organization, the api-key might have admin permissions, or staff, etc). In this step, I can filter the permissions with success

I have the following viewset:

class FooViewSet(viewsets.ModelViewSet):
    permission_classes = (FooPermissionsBasedOnOrganization | HasOrganizationBasedAPIKey, )

Assuming that both jwt token and api-key have staff permissions, I don't want them to be able to create resources, raising HTTP 403 forbidden. But with api-keys, the error is 401 unauthorized... With some debug, I've noticed the following:

The permission denied code is the following:

def permission_denied(self, request, message=None, code=None):
    if request.authenticators and not request.successful_authenticator:
        raise exceptions.NotAuthenticated()
    raise exceptions.PermissionDenied(detail=message, code=code)

API Keys will hit on the first raise, because it's not a User to be authenticated.

Should I need a Authentication class to use with API Keys, do I need something to bypass this, or is it something that I'm not seeing bacause this shouldn't be a problem?

Thanks :+1: