knktc's Notes

python, cloud, linux...

0%

Let Postman Set CSRF and Authorization Tokens Automatically

While developing a Django project recently, I had CSRF protection enabled, which meant every request needed an X-CSRFToken header. Without it, Postman requests would come back with 403.

In a Django app, the CSRF token is usually set as a cookie during login. This post shows how to make Postman automatically read that csrftoken cookie and reuse it in later requests.

To automate this, use Postman’s Tests feature. The Tests tab supports small JavaScript snippets for manipulating variables.

In your login request, add the following script:

1
2
3
var csrf_token = postman.getResponseCookie("csrftoken").value
postman.clearGlobalVariable("csrftoken");
postman.setGlobalVariable("csrftoken", csrf_token);

It should look something like this:

Set the Tests script

This script reads the csrftoken cookie from the login response and stores it as a Postman global variable named csrftoken. You can inspect the variable by clicking the eye icon in the top-right corner of Postman:

View the global variable

Then in later requests, add an X-CSRFToken header and use {{csrftoken}} as its value:

Use the header variable

From then on, every time you log in again, the variable gets refreshed automatically, which makes API testing much smoother.

In real development, you may also need bearer-style authentication tokens. Those can be extracted in the same way, except the token usually comes from the response JSON instead of a cookie:

1
2
3
var token = JSON.parse(responseBody).token;
postman.clearGlobalVariable("token");
postman.setGlobalVariable("token", token);

Example:

Set the authorization header

如果我的文字帮到了您,那么可不可以请我喝罐可乐?