[Django]-Django rest framework csrf token missing or incorrect

2👍

after reading the doc of django rest framework official i and a lot of help come from @Todor comment i realize that i should only put TokenAuthentification in the rest authentication classes because sessionAuthentication expect a csrf value in the request but android can’t give that so i use a token as in the doc in every request and that’s it !

5👍

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework.authentication.TokenAuthentication',
)
}

remove 'rest_framework.authentication.SessionAuthentication' from DEFAULT_AUTHENTICATION_CLASSES,if you still need browsable api view for DRF, use ModHeader in chrome。

👤Ykh

0👍

Are you properly storing and forwarding cookies from the Android networking library? I have very little familiarity with Ionic/Android, but the way that Django’s CSRF checks work is this:

  • Check if a CSRF token is provided in the body as csrfmiddlewaretoken
  • If no such parameter exists, check for a cookie called csrftoken
  • if no such cookie exists, fall back to the HTTP_X_CSRFTOKEN header

The cookie name and header name can be customized in settings.

So what I’m getting at is, what method are you using above to send the CSRF token? On mobile, it’s normally sorta tough to get a CSRF token for the request because the client generates the form (where on web, Django generates the form and injects the CSRF token).

That said, it is also common to make endpoints CSRF exempt, and it seems like you’re using a third party library for these endpoints, so I’m not sure why it’s requiring a CSRF token. You can check the project’s documentation.

The other possibility is that you’ve bound your own view at that URL, and you’re reaching that view instead of the one from the library you’re using. It’s sort of hard to tell. Why don’t you first try the request using DRF’s Browsable API?

0👍

I get this error when I was trying to host my website on Apache server.
If I run without Apache server (python manage.py runserver) everything is fine.

To solve this error:
Open Apache configuration file – httpd.conf
Add following line:

WSGIPassAuthorization On

0👍

Here’s my quick solution that isn’t good for production unless you fork the rest-framework repo with your changes… And well it disables the functionality for SessionAuthentication.

If you are going to be using your api with a browser-less front-end like a mobile app, which does not allow cross site requests to be made (as there is no browser from which a request can be made i.e. the app will not be able to open up links sent to you by others/you cannot navigate the web traditionally inside of it) Then it’s as simple as this:

To remove the functionality, go to the rest_framework site package. Inside of it is a authentication.py file, and inside of it, there’s is a class called ‘SessionAuthentication’. In here there’s a enforce_csrf() function which enforces the csrf by raising an exception when a csrf token isn’t present in a request. Simply comment out its body and it will no longer care about csrf.

Here’s what the authentication.py SessionAuthentication class looks like, do the following:

class SessionAuthentication(BaseAuthentication):

    def authenticate(self, request):
        """
        Returns a `User` if the request session currently has a logged in user.
        Otherwise returns `None`.
        """

        # Get the session-based user from the underlying HttpRequest object
        user = getattr(request._request, 'user', None)

        # Unauthenticated, CSRF validation not required
        if not user or not user.is_active:
            return None

        self.enforce_csrf(request)

        # CSRF passed with authenticated user
        return (user, None)

    def enforce_csrf(self, request):
        """
        Enforce CSRF validation for session based authentication.
        """
        ##### Comment Out Below:  ###########
        # check = CSRFCheck()
        # # populates request.META['CSRF_COOKIE'], which is used in process_view()
        # check.process_request(request)
        # reason = check.process_view(request, None, (), {})
        # if reason:
        #     # CSRF failed, bail with explicit error message
        #     raise exceptions.PermissionDenied('CSRF Failed: %s' % reason)

So, in case you’re wondering if this is a bad idea or not, because all requests are intentionally made inside a mobile app/controlled exclusively by the mobile app in most cases, it does not operate within the same environment as a browser. It’s hard for a user to accidentally follow a link or for a script . Note, this does not completely remediate the vulnerability, but the odds of it happening are incredibly unlikely and would most likely not occur directly through the mobile app

0👍

I wanted use SessionAuthentication to have the current user in rest views, i resolved it sending authorization header with the token value in each request, i am using JSON web token authentication too

-1👍

Well the solution is simple: you need to add the CSRF token when you make your request. How you would do that, specifically, we can’t answer, because we have no idea how you’re making the request. i.e. show some code.

Leave a comment