Django绕过权限装饰器进行用户注册并要求进行身份验证

时间:2017-08-22 19:48:29

标签: django django-rest-framework django-authentication

我正在努力为我的API服务注册用户。我检查了方法,一切都有效,但在POST用户注册数据时仍然收到错误代码

错误代码:

{"details": "Authentication credentials not provided"}

Settings.py

我在框架中添加了Basic Authentication,IsAuthenticated和TokenAuthentication

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

目前唯一有效的方法是为现有用户获取令牌:

Urls.py

url(r'^auth/', views.obtain_auth_token, name='get_auth_token'),

Url.py中的其他端点

url(r'^login/', Login.as_view(), name='login'),
url(r'^register/', Register.as_view(), name='signup'),

我相信我没有使用最佳做法进行用户注册或准备我将登录与注册混淆。我不确定。

在Views.py

中注册用户方法
# Register User

class Register(APIView):

queryset = User.objects.all()
serializer_class = UserSerializer
# permission_classes = [permissions.IsAuthenticated]

@permission_classes([permissions.IsAuthenticated, ])
@api_view(['POST', ])
def register_user(self, request, *args, **kwargs):
    serializer = UserSerializer(data=request.data)
    if serializer.is_valid():
        self.perform_create(serializer) # serializer.save()
        headers = self.get_success_headers(serializer.data)
        token, created = Token.objects.get_or_create(user=serializer.instance)
        return Response({'token': token.key, 'id': serializer.instance.id}, status=status.HTTP_201_CREATED, headers=headers)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Views.py

中的登录用户方法
queryset = User.objects.all()
serializer_class = UserSerializer

@api_view(['POST', ])
def login(request):
    username = request.POST.get('username')
    password = request.POST.get('password')
    user = authenticate(username=username, password=password)

    if user is not None:
        if user.is_active:
            login(request, user)
            return Response({"success": "User was successfully logged on."},)
        else:
            return Response({"error": "Login failed, bad request."},)
    else:
        return Response({"error": "Login failed, invalid username or password"}, status=status.HTTP_401_UNAUTHORIZED)

1 个答案:

答案 0 :(得分:4)

您的DRF设置是IsAuthenticated是每个视图的默认权限类之一。您遇到问题的视图是DRF在没有(也不应该)时检查令牌的结果。尝试明确清除这些视图的权限类:@permission_classes([])

obtain_auth_token正在运作的原因:https://github.com/encode/django-rest-framework/blob/master/rest_framework/authtoken/views.py#L10