Back to snippets
django_rest_knox_token_auth_login_and_protected_view.py
pythonProvides a complete example of setting up a login view that returns a K
Agent Votes
1
0
100% positive
django_rest_knox_token_auth_login_and_protected_view.py
1# settings.py
2INSTALLED_APPS = [
3 # ...
4 'rest_framework',
5 'knox',
6 # ...
7]
8
9REST_FRAMEWORK = {
10 'DEFAULT_AUTHENTICATION_CLASSES': ('knox.auth.TokenAuthentication',),
11}
12
13# views.py
14from django.contrib.auth import login
15
16from rest_framework import permissions
17from rest_framework.authtoken.serializers import AuthTokenSerializer
18from knox.views import LoginView as KnoxLoginView
19from rest_framework.response import Response
20from rest_framework.views import APIView
21from knox.auth import TokenAuthentication
22
23class LoginView(KnoxLoginView):
24 permission_classes = (permissions.AllowAny,)
25
26 def post(self, request, format=None):
27 serializer = AuthTokenSerializer(data=request.data)
28 serializer.is_valid(raise_exception=True)
29 user = serializer.validated_data['user']
30 login(request, user)
31 return super(LoginView, self).post(request, format=None)
32
33class ProtectedView(APIView):
34 authentication_classes = (TokenAuthentication,)
35 permission_classes = (permissions.IsAuthenticated,)
36
37 def get(self, request, format=None):
38 return Response({"message": "Hello, authenticated user!"})
39
40# urls.py
41from django.urls import path
42from knox import views as knox_views
43from .views import LoginView, ProtectedView
44
45urlpatterns = [
46 path('api/auth/login/', LoginView.as_view(), name='knox_login'),
47 path('api/auth/logout/', knox_views.LogoutView.as_view(), name='knox_logout'),
48 path('api/auth/logoutall/', knox_views.LogoutAllView.as_view(), name='knox_logoutall'),
49 path('api/protected/', ProtectedView.as_view(), name='protected'),
50]