1

Making a POST requests to register a new user through postman returns 403 Forbidden, CSRF verification failed. Request aborted... Going by DRF documentation and knox auth documentation i have everything set up correctly. It appears that Django's SessionAuthentication is being activated even though i do not have it in my DEFAULT_AUTHENTICATION_CLASSES. I have tried every potential solution i could find but nothing is working. The app is a Django rest api with React front end. Any help would be greatly appreciated.

Authentication and Permission settings

'DEFAULT_AUTHENTICATION_CLASSES': (
    'knox.auth.TokenAuthentication',
),

'DEFAULT_PERMISSION_CLASSES': (
    'rest_framework.permissions.AllowAny',
),

url calling the view as_view

re_path('auth/register', Register.as_view(), name='register'),

Class based Register view extending APIView which should handle csrf

class Register(APIView):
    """User Registration API View"""

    def post(self, request, *args, **kwargs):
        if request.method == 'POST':
            serializer = RegistrationSerializer(data=request.data)
            data = {}
            if serializer.is_valid():
                user = serializer.save()
                data['response'] = 'Account registered successfully'
                data['firstName'] = user.first_name
                data['lastName'] = user.last_name
                data['email'] = user.email
                data['token'] = AuthToken.objects.get(user=user).key
                return Response(data, status=status.HTTP_201_CREATED)

            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Stack trace error

Forbidden (CSRF cookie not set.): /api/account/auth/register
[20/Jun/2020 12:15:14] "POST /api/account/auth/register HTTP/1.1" 403 2864

Update I have found the issue and have added it as an answer below

SemajDraw
  • 131
  • 10
  • Does this answer your question? [How to disable Django's CSRF validation?](https://stackoverflow.com/questions/16458166/how-to-disable-djangos-csrf-validation) – Constantin Guidon Jun 20 '20 at 12:38
  • @ConstantinGuidon Extending the APIView class should make the dispatch method in the class csrf_exempt, However i have tried annotating the methods with csrf_exempt which it did not work. I tried using the @method_decorator(csrf_exempt, name='dispatch') on the class which also did not work. Also I have tried clearing my cookies and cache and signing out of all admin sessions to no avail – SemajDraw Jun 20 '20 at 12:45

1 Answers1

1

For anyone else who may find themselves in this situation I hope this can be of some help. It appears that because I am integrating React with Django and using Reacts router the Django urls must be placed before the React urls in the base urls.py file otherwise React's router takes the request and runs it through its router, cannot find any matching urls and throws an error thus it never gets run through the Django api endpoints. This explains why i was getting CSRF errors as Django's SessionAuthentication was being hit through React router. After all the testing the answer was as simple as swapping two lines.

Previous Throwing Errors

urlpatterns = [
    # Admin portal
    re_path('admin/', admin.site.urls),

    # React UI Entry
    re_path('', include('frontend.urls'), name='frontend'),

    # Rest API Urls
    re_path('api/account/', include('account.api.urls'), name='account_api'),
]

Refactored No Errors

urlpatterns = [
    # Admin portal
    re_path('admin/', admin.site.urls),

    # Rest API Urls
    re_path('api/account/', include('account.api.urls'), name='account_api'),

    # React UI Entry
    re_path('', include('frontend.urls'), name='frontend'),
]
SemajDraw
  • 131
  • 10
  • In my case, changing the order of urls worked but in a different way. After a server migration, my DRF was complaining about CSRF even using the same libraries, the only difference was that the new server is a Debian 11 and the old was Ubuntu 20.2. The solution: moving my function based ApiView to the beggining worked after a day of investigation. Yes, I know, this is odd. Many thanks for share your experience, helped me a lot. – André Duarte May 05 '22 at 11:11