Django restframework,未提供身份验证凭据,knox-tokenauthentication [英] Django restframework, Authentication credentials were not provided, knox-tokenauthentication
问题描述
我从Traversy Media的youtube上学习了Redox和Django的教程.我遵循了该教程,现在我不知道它是否被限制了.
I took a tutorial in Redox and Django from youtube from Traversy Media. I follow along with the tutorial and now I don't know were it curshed.
curl http://localhost:8000/api/auth/login/ -d \
'{"username": "Tom", "password": "PassWord@321"}' \
-H "Content-type: application/json" -X POST
这样做,我需要获取用户和相应的令牌,但相反,我会得到
By doing so I need to get user and the corresponding token but instead I'm getting
{"detail":"Authentication credentials were not provided."}
我所做的一切=>
# settings.py
INSTALLED_APPS = [
'leads',
'rest_framework',
'frontend',
'accounts',
'knox',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": ("knox.auth.TokenAuthentication", ),
}
# serializers.py
class LoginSerializer(serializers.Serializer):
username = serializers.CharField()
password = serializers.CharField()
def validate(self, data):
user = authenticate(**data)
if user and user.is_active:
return user
raise serializers.ValidationError("Incorrect Credentials")
# api.py
class LoginAPI(generics.GenericAPIView):
serializer_class = LoginSerializer
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data = request.data)
serializer.is_valid(raise_exception = True)
user = serializer.validated_data
_, token = AuthToken.objects.create(user)
return Response({
"user": UserSerializer(user, context = self.get_serializer_context()).data,
"token": token
})
# leadmanager/urls.py
urlpatterns = [
path("api/auth/", include("accounts.urls")),
]
# accounts/urls.py
urlpatterns = [
path("login/", LoginAPI.as_view()),
]
我不知道它被压碎了.
推荐答案
请添加此代码
class LoginAPI(generics.GenericAPIView):
serializer_class = LoginSerializer
permission_classes = () # empty tuple
...........
此处您需要为 LoginAPI
视图覆盖 permission_classes
,因为 permission_classes
负责检查请求是否已通过身份验证.由于向所有用户公开了 LoginAPI
,因此View没有权限检查.
Here you need to override permission_classes
for LoginAPI
view as permission_classes
are responsible to check whether the request is authenticated. As LoginAPI
is exposed for all users that View has no permission check.
这篇关于Django restframework,未提供身份验证凭据,knox-tokenauthentication的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!