Search code examples
djangodjango-rest-frameworkdjango-rest-framework-simplejwt

Django Rest-Framework-Simplejwt not working with modheader


I am working on some projects and trying to the list view of the book. I used Django Rest-Framework-Simplejwt to generate tokens and mod header for authentication. When I tried to request a token for a user such as the admin user, and enter it into the mod header, the request is still unauthorized. I tried to do it a couple of times, but still not working.

Views.py

from rest_framework import generics, permissions
from rest_framework.permissions import IsAuthenticated
from rest_framework.exceptions import ValidationError

from django.contrib.auth.models import User

from .models import Book
from .serializers import (
                          BookSerializer,
                          RegistrationSerializer 
                          )
    
    
class BookCreateView(generics.CreateAPIView):
    """Create a Book"""
    queryset = Book.objects.all()
    serializer_class = BookSerializer
    permission_classes = (IsAuthenticated,)
    
    def perform_create(self, serializer):
        serializer.save(user=self.request.user)

class BookListView(generics.ListAPIView):
    """Show all books"""
    serializer_class = BookSerializer
    permission_classes = (IsAuthenticated,)
    
    def get_queryset(self):
        user = self.request.user
        return Book.objects.filter(user=user)


class BookDetailView(generics.RetrieveAPIView):
    """Show detail of the book"""
    serializer_class = BookSerializer
    permission_classes = (IsAuthenticated,)
    
    def get_queryset(self):
        user = self.request.user
        return Book.objects.filter(user=user)
    

class BookUpdateView(generics.RetrieveUpdateDestroyAPIView):
    """update detail of the book"""
    queryset = Book.objects.all()
    serializer_class = BookSerializer
    permission_classes = (IsAuthenticated,)
    
    
    def delete(self, request, *args, **kwargs):
        book = Book.objects.filter(user=self.request.user, pk=kwargs['pk'])
        if book.exists():
            return self.destroy(request, *args, **kwargs)
        else:
            raise ValidationError('Book is not yours!')
    
    def perform_update(self, serializer, **kwargs):
        book = Book.objects.get(pk=self.kwargs['pk'])
        if self.request.user != book.user:
            raise ValidationError("You are not the owner of this book")
        serializer.save(user=self.request.user, book=book)
    

class UserRegistrationView(generics.CreateAPIView):
    queryset = User.objects.all()
    serializer_class = RegistrationSerializer
    permission_classes = [permissions.AllowAny]

Serializers.py

from rest_framework import serializers
from django.contrib.auth.models import User
from .models import Book

class BookSerializer(serializers.ModelSerializer):
    """Serializer for Book"""
    
    class Meta:
        model = Book
        fields = (
            'id','user',
            'title', 'author',
            'description', 'image')
        read_only_fields = ('id', 'user')
        
        
class RegistrationSerializer(serializers.ModelSerializer):
    password = serializers.CharField(style={'input type':'password'}, write_only=True)
    class Meta:
        model = User
        fields = ('username', 'email', 'password')
        
    def create(self, validated_data):
        user = User.objects.create(
                                   username=validated_data['username'],
                                   email=validated_data['email'])
        user.set_password(validated_data['password'])
        user.save()
        return user

enter image description here enter image description here enter image description here enter image description here

I entered the correct Token (copy&paste), but still not able to authenticate.


Solution

  • You are using "Token <eyJ..>". But instead your token should be like "Bearer <eyJ..>"

    Some of Simple JWT’s behavior can be customized through settings variables in settings.py