Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

Django - Knox auth setup

pip install djangorestframework
pip install django-rest-knox

#Add rest_framework and knox to your INSTALLED_APPS, remove rest_framework.authtoken if you were using it.
INSTALLED_APPS = [
    ...
    'rest_framework',
    'knox',
]

#Make knox’s TokenAuthentication your default authentification class for django-rest-framework, in settings.py file:
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        # 'rest_framework.authentication.BasicAuthentication',
        # 'rest_framework.authentication.SessionAuthentication',
        'knox.auth.TokenAuthentication',
    ]
}

#Create a file in your app named serializers.py and add
from rest_framework import serializers
from django.contrib.auth.models import User

# User Serializer
class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'email')

# Register Serializer
class RegisterSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'email', 'password')
        extra_kwargs = {'password': {'write_only': True}}

    def create(self, validated_data):
        user = User.objects.create_user(validated_data['username'], validated_data['email'], validated_data['password'])

        return user


#After creating serializer, we need to create DRF APIView In views.py file
from rest_framework import generics, permissions
from django.contrib.auth import login
from rest_framework.response import Response
from knox.models import AuthToken
from .serializers import UserSerializer, RegisterSerializer
from rest_framework import permissions
from rest_framework.authtoken.serializers import AuthTokenSerializer
from knox.views import LoginView as KnoxLoginView

# Register API
class RegisterAPI(generics.GenericAPIView):
    serializer_class = RegisterSerializer

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()
        return Response({
        "user": UserSerializer(user, context=self.get_serializer_context()).data,
        "token": AuthToken.objects.create(user)[1]
        })

class LoginAPI(KnoxLoginView):
    permission_classes = (permissions.AllowAny,)

    def post(self, request, format=None):
        serializer = AuthTokenSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data['user']
        login(request, user)
        user = serializer.validated_data['user']
        token= AuthToken.objects.create(user)[1]
        return super(LoginAPI, self).post(request, format=None)
 
#In urls.py file add
from .views import RegisterAPI
from django.urls import path
from knox import views as knox_views
from .views import LoginAPI

urlpatterns = [
    path('api/register/', RegisterAPI.as_view(), name='register'),
    path('api/login/', LoginAPI.as_view(), name='login'),
    path('api/logout/', knox_views.LogoutView.as_view(), name='logout'),
    path('api/logoutall/', knox_views.LogoutAllView.as_view(), name='logoutall'),
]

Python manage.py makemigrations
Python manage.py migrate

#header for authentication
Authorization: "Token <token>"

#for function-based views
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import api_view, permission_classes

@api_view(['GET'])
@permission_classes((IsAuthenticated, ))
def your_view(req):




Comment

PREVIOUS NEXT
Code Example
Python :: pandas transform count where condition 
Python :: multiple logger instances populating single log python 
Python :: conditional and in python 
Python :: generate barcode using python 
Python :: how to delete item in string python 
Python :: accuracy for each class 
Python :: split list python percent 
Python :: split a pd dataframe 
Python :: python cursor placement 
Python :: python replace negative infinity 
Python :: python keyerror 
Python :: id3 algorithm code in python 
Python :: cascaed models in django 
Python :: pypdf2 advanced tutorial 
Python :: backend in python 
Python :: python datetime to unix timestamp 
Python :: python invert colormap 
Python :: python pickle dataframe 
Python :: seaborn countplot hue stacked 
Python :: Send Fetch Post With Data Using Body 
Python :: python increase one item in list 
Python :: value list in django 
Python :: How to check for string membership in python 
Python :: how to run python in the browser 
Python :: change increment in for loop python 
Python :: connect with database python 
Python :: guessing game python 
Python :: destory image in pygame 
Python :: dictionary from two list 
Python :: project euler problem 11 python 
ADD CONTENT
Topic
Content
Source link
Name
3+3 =