Skip to content

Commit

Permalink
Merge pull request #336 from vovarudomanenko/sanctum-cookies
Browse files Browse the repository at this point in the history
Make TryIt work with Sanctum's cookie based authentication out of the box
  • Loading branch information
romalytvynenko authored Mar 24, 2024
2 parents c5ab98f + b67796b commit 6a4e32c
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions resources/views/docs.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,46 @@

<script src="https://unpkg.com/@stoplight/elements/web-components.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/@stoplight/elements/styles.min.css">

<script>
const originalFetch = window.fetch;
// intercept TryIt requests and add the XSRF-TOKEN header,
// which is necessary for Sanctum cookie-based authentication to work correctly
window.fetch = (url, options) => {
const CSRF_TOKEN_COOKIE_KEY = "XSRF-TOKEN";
const CSRF_TOKEN_HEADER_KEY = "X-XSRF-TOKEN";
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 csrfToken = getCookieValue(CSRF_TOKEN_COOKIE_KEY);
if (csrfToken) {
const { headers = new Headers() } = options || {};
updateFetchHeaders(headers, CSRF_TOKEN_HEADER_KEY, decodeURI(csrfToken));
return originalFetch(url, {
...options,
headers,
});
}
return originalFetch(url, options);
};
</script>
</head>
<body style="height: 100vh; overflow-y: hidden">
<elements-api
Expand Down

0 comments on commit 6a4e32c

Please sign in to comment.