Closed sprklinginfo closed 3 months ago
found the answer to my first question https://scramble.dedoc.co/usage/security.
But still unable to solve 'CSRF token mismatch' issue. In Postman, I can add a X-XSRF-TOKEN
in Headers
to avoid this error. Does scramble have something like that?
@sprklinginfo are you using the latest Scramble release, 0.8.5
?
yes, I am using 0.8.5.
I'm also having the same CSRF token mismatch
issue when trying to send a request in the API documentation pages
Hi, same problem with Laravel 10 and Scramble 0.8.5
I bumped into the same problem. What I noticed is that it maybe has to do something with cookies I assume.
When I change the app url in the .env to something incorrect then the request works as intended.
Commenting EnsureFrontendRequestsAreStateful::class
seems not a good solution.
Same for VerifyCsrfToken
protected $except = [ "/api/*" ];
The cookie / xcsrf token is not added to the request that is send to the server.
Since Tryit uses fetch
under the hood to send requests. You can intercept and add an XSRF-TOKEN
header to the every request by monkey-patching the fetch
function. Here is an example.
<script>
const getCookieValue = (key) => {
const cookie = document.cookie.split(';').find((cookie) => cookie.trim().startsWith(key));
return cookie?.split("=")[1];
};
const updateFetchHeaders = (
headers,
headerKey,
headerValue,
) => {
if (headers instanceof Headers) {
headers.set(headerKey, headerValue);
} else if (Array.isArray(headers)) {
headers.push([headerKey, headerValue]);
} else if (headers) {
headers[headerKey] = headerValue;
}
};
const originalFetch = window.fetch;
window.fetch = (url, options) => {
const csrfToken = getCookieValue("XSRF-TOKEN");
if (csrfToken) {
const { headers = new Headers() } = options || {};
updateFetchHeaders(headers, "X-XSRF-TOKEN", unescape(csrfToken));
return originalFetch(url, {
...options,
headers,
});
}
return originalFetch(url, options);
};
</script>
Now sanctum authentication via cookies will work as expected
I have a Laravel 9 project (php 8). Most of our APIs (api/*) are using
auth:sanctum
in theroutes/api.php
. but the api documents generated by the package don't seem to reflect it. I followed the installation instructions. Is there anything missing?Meanwhile, I get a 419 error: CSRF token mismatch when trying 'Send API request' for POST calls. any solution other than commenting off
EnsureFrontendRequestsAreStateful::class,
in Kernel.php? I hope to use it on the production so the API documents can be online for others (access controlled by the gate, of course). Thanks.