Skip to content

Instantly share code, notes, and snippets.

@jsmedmar

jsmedmar/token.py

Last active Feb 24, 2021
Embed
What would you like to do?
A django LoginRequiredMixin that allows token authentication.
from django.contrib.auth import mixins
from rest_framework.authentication import SessionAuthentication
from rest_framework.authentication import TokenAuthentication
from rest_framework import generics
class TokenLoginRequiredMixin(mixins.LoginRequiredMixin):
"""A login required mixin that allows token authentication."""
def dispatch(self, request, *args, **kwargs):
"""If token was provided, ignore authenticated status."""
http_auth = request.META.get("HTTP_AUTHORIZATION")
if http_auth and "Token" in http_auth:
pass
elif not request.user.is_authenticated:
return self.handle_no_permission()
return super(mixins.LoginRequiredMixin, self).dispatch(
request, *args, **kwargs)
class ListAPIView(TokenLoginRequiredMixin, generics.ListAPIView):
"""This view suppot both token and session authentication."""
authentication_classes = [
SessionAuthentication,
TokenAuthentication,
]
@EO2875

This comment has been minimized.

Copy link

@EO2875 EO2875 commented Jun 25, 2020

Thanks! It's a really useful snippet.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment