paint-brush
Automatically Set CSRF Token in Postman — Django Tipsby@chillaranand
20,684 reads
20,684 reads

Automatically Set CSRF Token in Postman — Django Tips

by chillar anandFebruary 28th, 2019
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Django has inbuilt <a href="https://docs.djangoproject.com/en/dev/ref/csrf/">CSRF protection</a> mechanism for requests via unsafe methods to prevent <a href="https://en.wikipedia.org/wiki/Cross-site_request_forgery">Cross Site Request Forgeries</a>. When CSRF protection is enabled on AJAX POST methods, X-CSRFToken header should be sent in the&nbsp;request.
featured image - Automatically Set CSRF Token in Postman — Django Tips
chillar anand HackerNoon profile picture

How To Automatically Set CSRF Token in Postman?

Django has inbuilt CSRF protection mechanism for requests via unsafe methods to prevent Cross Site Request Forgeries. When CSRF protection is enabled on AJAX POST methods, X-CSRFToken header should be sent in the request.

Postman is one of the widely used tool for testing APIs. In this article, we will see how to set CSRF token and update it automatically in Postman.

CSRF Token In Postman

Django sets csrftoken cookie on login. After logging in, we can see the csrf token from cookies in the Postman.

We can grab this token and set it in headers manually.

But this token has to be manually changed when it expires. This process becomes tedious to do it on an expiration basis.

Instead, we can use Postman scripting feature to extract the token from the cookie and set it to an environment variable. In Test section of the postman, add these lines.

var xsrfCookie = postman.getResponseCookie("csrftoken"); postman.setEnvironmentVariable('csrftoken', xsrfCookie.value);

This extracts csrf token and sets it to an environment variable called csrftoken in the current environment.

Now in our requests, we can use this variable to set the header.

When the token expires, we just need to log in again and csrf token gets updated automatically.

Conclusion

In this article, we have seen how to set and renew csrf token automatically in Postman. We can follow similar techniques on other API clients like CURL or httpie to set csrf token.

Originally published at avilpage.com on February 28, 2019.