Skip to content

Instantly share code, notes, and snippets.

@jsmedmar
Last active October 23, 2021 10:30
Show Gist options
  • Save jsmedmar/d846eee063fa23148f8a87313dd590a3 to your computer and use it in GitHub Desktop.
Save jsmedmar/d846eee063fa23148f8a87313dd590a3 to your computer and use it in GitHub Desktop.
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
Copy link

EO2875 commented Jun 25, 2020

Thanks! It's a really useful snippet.

@moritz89
Copy link

moritz89 commented Apr 3, 2021

For usage with the GraphQL views: graphql-python/graphene#249 (comment)

@goetia00
Copy link

If you are using generics.ListAPIView why would you need to override the token auth provided by authentication.TokenAuthentication? Also, is this only bypassing token validation? How is it secure? I'm a bit confused.

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