Automatically Set CSRF Token in Postman — Django Tips by@chillaranand

Automatically Set CSRF Token in Postman — Django Tips

June 23rd 2022 18,410 reads
Read on Terminal Reader
react to story with heart
react to story with light
react to story with boat
react to story with money
image
Chillar Anand HackerNoon profile picture

Chillar Anand

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.
image
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.
image
Now in our requests, we can use this variable to set the header.
image
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.
react to story with heart
react to story with light
react to story with boat
react to story with money
L O A D I N G
. . . comments & more!