Home > OS >  Can't authenticate a user in Django rest framework
Can't authenticate a user in Django rest framework

Time:11-28

I'm trying to get data of an authenticated user using the token, I'm using postman to send a get request and get the data I need but I'm receiving a response

"detail": "Authentication credentials were not provided."

this is the view `

class ReceiveMessagesView(viewsets.ModelViewSet):
    serializer_class = MessageSerializer
    permission_classes = [permissions.IsAuthenticated]
    http_method_names = ['get', 'post']

    def get_queryset(self):
        user = self.request.user
        queryset = Message.objects.filter(receiver=user)
        return queryset`

settings

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
}

urls

router = routers.DefaultRouter()
router.register('', views.ReceiveMessagesView, basename='receive_messages')

urlpatterns = [

    path('', include(router.urls))

]

serializer

class MessageSerializer(serializers.ModelSerializer):
    class Meta:
        model = Message
        fields = [
                  'sender',
                  'receiver',
                  'subject', 'msg',
                  'creation_date',
                  ]

In the postman request I'm sending in Authorization the key as "Token" and the value as the user I want data about's token

I am trying to send an authorized get request and received an authorized user's data btw if I'm trying to print the user instance and the token when I get to the view (with self.request.user and self.request.auth)I get the correct instance user but for the token I get None

CodePudding user response:

Set a key:value at the HEADER of the HTTP request. You just need a valid token:

KEY: Authorization
VALUE: Token yourtokenvalue

CodePudding user response:

If you try to Authenticate with Token authentication using POSTMAN, you need to pass only 'rest_framework.authentication.TokenAuthentication', in DEFAULT_AUTHENTICATION_CLASSES

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
}
  • Related