简体   繁体   中英

Basic auth protected views in DRF

I have some API endpoints that i need to protect using HTTP Basic Authentication in Django Rest Framework. There is BasicAuthentication in DRF, but that actually authenticates against a user in Django, which is not what I'm looking for.

I found a solution using a custom permission, but ti means monkey patching the views to set the correct authenticate header.

Is there a better way?

class BasicAuthPermission(permissions.BasePermission):
    def has_permission(self, request, view):
        credentials = view.credentials  # Will raise AttributeError on missing credentials
        realm = getattr(view, 'realm', 'Protected')
        auth = request.headers.get('Authorization')
        with suppress(ValueError, AttributeError):
            auth = b64decode(auth.split()[-1]).decode()
        if auth != credentials:
            # Monkey patch style
            view.get_authenticate_header = lambda r: f'Basic realm="{realm}"'
            raise exceptions.AuthenticationFailed('Bad credentials.')
        return True

Im my view:

class ProtectedApiView(generics.GenericAPIView):
    permission_classes = [BasicAuthPermission]
    credentials = 'user:password'
    # ...

Following Arakkal's suggestion in comment, I did this with an Authentication class instead. It does feel less hacky, but I can not set credentials on the View, like I did originally.

I realize "anonymous authentication" is a weird name, but that's because Django doesn't know anything about the user. So for all practical purposes anonymous.

from base64 import b64decode
import binascii

from rest_framework import generics, exceptions, authentication

class AnonymousBasicAuthentication(authentication.BaseAuthentication):
    """
    HTTP Basic authentication against preset credentials.
    """
    www_authenticate_realm = 'api'
    credentials: str = None

    def authenticate(self, request):
        try:
            auth, encoded = authentication.get_authorization_header(request).split(maxsplit=1)
        except ValueError:
            raise exceptions.AuthenticationFailed('Invalid basic header.')

        if not auth or auth.lower() != b'basic':
            raise exceptions.AuthenticationFailed('Authentication needed')

        try:
            credentials = b64decode(encoded).decode(authentication.HTTP_HEADER_ENCODING)
        except (TypeError, UnicodeDecodeError, binascii.Error):
            raise exceptions.AuthenticationFailed('Invalid basic header. Credentials not correctly base64 encoded.')

        if self.credentials != credentials:
            raise exceptions.AuthenticationFailed('Invalid username/password.')

    def authenticate_header(self, request):
        return 'Basic realm="{}"'.format(self.www_authenticate_realm)


class MyAuthentication(AnonymousBasicAuthentication):
    credentials = 'user:password'


class MyProtectedView(generics.GenericAPIView):
    authentication_classes = [MyAuthentication]
    # ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM