Django-rest-framework {“detail”:“未提供身份验证凭据。”使用 django-rest-knox

问题描述 投票:0回答:2

我看到错误

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

这是我用于登录的代码

我的模特:

class User(AbstractBaseUser):
    STUDENT = 'STU'
    SCHOOL = 'SCH'
    INSTITUTE = 'INST'
    TUTOR = 'TUT'
    ACCOUNT_TYPE_CHOICES = [
        (STUDENT, 'Student'),
        (SCHOOL, 'School'),
        (INSTITUTE, 'Institute'),
        (TUTOR, 'Tutor'),
    ]
    account_type = models.CharField(
        max_length=4,
        choices=ACCOUNT_TYPE_CHOICES,
        default=SCHOOL,
    )
    name = models.CharField(max_length=255)
    email = models.EmailField(unique=True,max_length=255)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    is_admin = models.BooleanField(default=False)
    timestamp = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['name','account_type']

    objects=UserManager()

    def __str__(self):
        return self.email

    def has_perm(self,perm,obj=None):
        return True

    def has_module_perms(self,app_label):
        return True

    @property
    def is_staff(self):
        return self.is_admin

我的序列化器:

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

# User Serializer


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'account_type', 'name', 'email')

# Login Serializer


# I guess the validate function is not working .

class LoginSerializer(serializers.Serializer):
    email = serializers.EmailField()
    password = serializers.CharField()

    def validate(self, data):
        user = authenticate(request=None,**data)
        if user and user.is_active:
            return user
        raise serializers.ValidationError("Incorrect Credentials")

我的看法:

from rest_framework import generics, permissions,authentication
from rest_framework.response import Response
from knox.models import AuthToken
from knox.views import LoginView as KnoxLoginView
from .serializers import UserSerializer, RegisterSerializer, LoginSerializer
from django.contrib.auth import authenticate,login

# Login API


class LoginAPI(generics.GenericAPIView):
    serializer_class = LoginSerializer
    # authentication_class=[authentication.BasicAuthentication]
    def post(self, request, *args, **kwargs):
        serializer = LoginSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data
        return Response({
            "user": UserSerializer(user, context=self.get_serializer_context()).data,
            "token": AuthToken.objects.create(user)[1]
        })

我的网址:

from django.urls import path, include
from .api import RegisterAPI, LoginAPI
from knox import views as knox_views

urlpatterns = [
    path('api/auth/', include('knox.urls')),
    path('api/auth/register/', RegisterAPI.as_view()),
    path('api/auth/login/', LoginAPI.as_view()),
    path('api/auth/logout/', knox_views.LogoutView.as_view(), name='knox_logout')
]

此外,当我提供注册时生成的令牌时,它会提示用户处于不活动或死亡状态。但是当我检查我的数据库和令牌到期时间时,它仍然处于活动状态。 我尝试过不同的第三方库,例如rest-auth,它也给出了相同的错误。我也检查了有关同一主题的许多其他答案,但应用它们也没有帮助。

python django django-rest-framework django-rest-auth django-rest-knox
2个回答
1
投票

您应该从 REST_FRAMEWORK 设置中的 settings.py 文件中确认您已将“DEFAULT_PERMISSION_CLASSES”设置为“rest_framework.permissions.AllowAny”。

应该是这样的:

# Rest framework
REST_FRAMEWORK = {
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.AllowAny',
    ],
}

0
投票

我已经遇到了类似的问题,解决方案是在 Postman 标头中设置 授权令牌

© www.soinside.com 2019 - 2024. All rights reserved.