Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django REST Framework - TokenAuthentication - use of Cache

Is there a way to use memcached for TokenAuthentication with Django REST Framework.

My tokens for users stay same for long periods of time (months e.g.), and hence it makes sense not to hit the database for each request that comes in to my server, and get the user object using the cached token.

Is there a neat way of achieving this?

Thanks

like image 813
dowjones123 Avatar asked Mar 21 '26 11:03

dowjones123


1 Answers

You can create a custom authentication class that hits memcached instead of you DB:

class ExampleAuthentication(authentication.BaseAuthentication):
    def authenticate(self, request):
        token = request... # get your token here
        if not token:
            return None

        try:
            # user = User.objects.get(username=username) -> This is the original code from the link above
            user = ... # get your user based in token here
        except User.DoesNotExist:  # some possible error
            raise exceptions.AuthenticationFailed('No such user')

        return (user, None)

Then you can use your own authentication class per view, ie:

class ExampleApiView(APIView):
    authentication_classes = (CustomTokenAuthentication, )

    def get(self, request, *args, **kwargs):

        ...
like image 124
Gocht Avatar answered Mar 24 '26 15:03

Gocht



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!