我创建了一个JWT-授权应用程序的后端。登录、注销、令牌检索和刷新都工作正常,符合预期。今天早上我添加了一个注册视图,它抛出了通常的情况"detail": "Authentication credentials were not provided.
对于未经身份验证的请求,您可能会遇到错误,因为这是默认情况(见下文)。
但是,因为这是一个注册端点,我不希望它只允许授权的请求。 (检查了有效令牌后,当您提供身份验证时,视图的其余部分将按预期工作。)查看DRF docs,我认为使用带有AllowAny的permission_classes包装器在这里可以工作,但事实并非如此。
我缺少什么?我觉得 Permission_classes 装饰器应该覆盖“IsAuthenticated”的默认设置?
我正在从curl 在本地主机上进行测试:
curl -X POST -H "Content-Type: application/json" -d '{"email":"[email protected]", "first_name": "boba", "last_name": "fett" "password":"xyz"}' http://localhost:8000/account/register/
视图是:
@permission_classes(AllowAny)
@api_view(['POST'])
def register_user(request):
from django.contrib.auth.models import User
from rest_framework_jwt.views import obtain_jwt_token
if request.user.is_authenticated():
return Response ({"already_registered": "User with that username has already registered"}, status=status.HTTP_701_ALREADY_REGISTERED)
data = request.data
user, created = User.objects.get_or_create(username=data["email"],
email=data["email"],
first_name=data["first_name"],
last_name=data["last_name"],
password=data["password"])
if created:
token = obtain_jwt_token(data["email"],data["password"] )
return Response ({"token": token}, status=status.HTTP_200_OK)
else:
return Response ({"already_registered": "User with that username has already registered"}, status=status.HTTP_701_ALREADY_REGISTERED)
settings.py 中的权限是:
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
),
}
相关问题:Django Rest Framework - 未提供身份验证凭据- 我认为默认权限是正确的,我只想在这种情况下覆盖它们。
Django Rest Framework - 由于 CSRF 令牌不正确而导致 DELETE ajax 调用失败- CSRF 未用作基于 JWT 的身份验证。
Django:Rest Framework 验证标头- Apache 特定问题(当前仍在 devserver localhost 上)
未提供 Django Rest Framework 身份验证凭据- 还没有回答!