Created
January 31, 2025 07:16
-
-
Save abramcatalyst/57b5782fd97d4b1f85a13adc9bb84317 to your computer and use it in GitHub Desktop.
Best-Postman-pre-request-script-csrf-token-laravel-sanctum.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 we already have a CSRF token in the environment, use it | |
if (pm.environment.get('XSRF-TOKEN')) { | |
pm.request.headers.upsert({ | |
key: 'x-xsrf-token', | |
value: pm.environment.get('XSRF-TOKEN'), | |
}); | |
} else { | |
// Define CSRF request URL | |
let csrfRequestUrl = pm.environment.get('url') + '/sanctum/csrf-cookie'; | |
// Perform the CSRF request | |
pm.sendRequest(csrfRequestUrl, (error, response) => { | |
if (error) { | |
console.error('Error fetching CSRF token:', error); | |
return; | |
} | |
if (response.code !== 204) { | |
console.error('Unexpected response code:', response.code); | |
return; | |
} | |
// Find the XSRF-TOKEN cookie from response headers | |
let xsrfCookieHeader = response.headers.find(header => | |
header.key.toLowerCase() === 'set-cookie' && | |
header.value.includes('XSRF-TOKEN') | |
); | |
if (xsrfCookieHeader) { | |
let xsrfToken = decodeURIComponent(xsrfCookieHeader.value.split(';')[0].split('=')[1]); | |
// Set CSRF token in headers for request | |
pm.request.headers.upsert({ | |
key: 'x-xsrf-token', | |
value: xsrfToken, | |
}); | |
// Store token in environment for reuse | |
pm.environment.set('XSRF-TOKEN', xsrfToken); | |
console.log("Decoded XSRF Token:", xsrfToken); | |
} else { | |
console.error('XSRF-TOKEN not found in response headers.'); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment