Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save marianomat/bf6a91c58c1017bdfe8e245ef4779326 to your computer and use it in GitHub Desktop.
Save marianomat/bf6a91c58c1017bdfe8e245ef4779326 to your computer and use it in GitHub Desktop.
Postman Pre-Request script to append CSRF token in header for POST requests in Laravel Sanctum authenticated SPA. Requires active environment with {{url}} variable defined for main app domain.
/**
* Postman Pre-Request script to append CSRF token in header for POST requests in Laravel
* Sanctum authenticated SPA. Requires active environment with {{url}} variable defined
* for main app domain.
*
* Postman Interceptor allows appending cookies from browser, but Laravel CSRF middleware
* only validates CSRF in headers or in _token form field, not in cookies. Axios automatically
* appends the CSRF from cookie to headers, but Postman cannot access intercepted cookies
* and use them, so we have to do one pre-request to get the CSRF token, store it
* in environment so it can be reused, and then append it to headers.
*/
// Query CSRF token and append it before request is made
if (pm.request.method !== 'GET') {
if(pm.environment.get('XSRF-TOKEN')) {
pm.request.headers.upsert({
key: 'x-xsrf-token',
value: pm.environment.get('XSRF-TOKEN'),
});
} else{
let csrfRequestUrl = pm.environment.get('url') + '/sanctum/csrf-cookie';
pm.sendRequest(csrfRequestUrl, function(err, res, {cookies}) {
let xsrfCookie = cookies.one('XSRF-TOKEN');
if (xsrfCookie) {
let xsrfToken = decodeURIComponent(xsrfCookie['value']);
pm.request.headers.upsert({
key: 'x-xsrf-token',
value: xsrfToken,
});
pm.environment.set('XSRF-TOKEN', xsrfToken);
}
});
}
}
/**
* Test/post Request for the above. Check for expired CSRF token and if it happens,
* clear the env variable so it gets refreshed next time
*/
if(pm.response.code === 419) {
pm.environment.unset("XSRF-TOKEN");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment