How do I authenticate API requests (by anonymous user) in Django rest framework?

API requests will be sent by anonymous users. No login / registration function.

I need to authenticate API requests, one primitive way I've tried is to send an authorization key in every request. This auth key I have stored in the Angular frontend as a constant.

There must be a better and harder way, kindly help!

+3


source to share


2 answers


The Django REST framework largely assumes that requests are user-authenticated, but they provide support for anonymous authentication requests. While this largely violates the assumption that "authentication" means "(Django's) user verification is authentic," the Django REST framework allows it to happen and replaces it instead AnonymousUser

.

Authentication in DRF can specify both request.user

(authenticated user) and request.auth

(typically used tokens, if applicable) in the request. This way, for your authentication, you will stick with the tokens you created (in the model or elsewhere) and they will be validated instead of the user credentials and you just don't finish setting up the user.



from django.contrib.auth.models import AnonymousUser
from rest_framework import authentication
from rest_framework import exceptions

class ExampleAuthentication(authentication.BaseAuthentication):
    def authenticate(self, request):
        auth = authentication.get_authorization_header(request)

        if not auth or auth[0].lower() != b'token':
            return None

        if len(auth) == 1:
            msg = _('Invalid token header. No credentials provided.')
            raise exceptions.AuthenticationFailed(msg)
        elif len(auth) > 2:
            msg = _('Invalid token header. Credentials string should not contain spaces.')
            raise exceptions.AuthenticationFailed(msg)

        try:
            token = Token.objects.get(token=auth[1])
        except Token.DoesNotExist:
            raise exceptions.AuthenticationFailed('No such token')

        return (AnonymousUser(), token)

      

This example assumes that you have a model Token

that stores the tokens to be authenticated. Token objects will be set to request.auth

if the request has been properly authenticated.

+7


source


Read the rest of the api docs on authentication and their tutorial - they offer a solid introduction to parameters.



0


source







All Articles