Search code examples
djangodjango-rest-frameworkdjango-authentication

Django bypasses permissions decorator for user registration and asks for authentication


I'm struggling with registering users for my API service. I've checked the methods and everything is valid, but I still receive an error code when POST'ing user registration data

Error Code:

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

Settings.py

I've added Basic Authentication, IsAuthenticated and TokenAuthentication to the framework

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

The only thing that works currently is obtaining a token for an existing user:

Urls.py

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

Other endpoints in Url.py

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

I believe I'm not using the best practice for user registration or prepares I'm confusing the login with the signup. I'm not sure.

Register User method in 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)

Login User method in 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)

Solution

  • Your DRF setup is such that IsAuthenticated is one of the default permissions classes for every view. The views you're having trouble with are a result of DRF checking for a token when there is none (and shouldn't be). Try explicitly clearing the permissions classes for these views: @permission_classes([]).

    The reason obtain_auth_token is working: https://github.com/encode/django-rest-framework/blob/master/rest_framework/authtoken/views.py#L10