Skip to content

Commit

Permalink
make TryIt work with Sanctum's cookie based authentication out of the…
Browse files Browse the repository at this point in the history
… box
  • Loading branch information
layerok committed Mar 13, 2024
1 parent e6e0354 commit e80ffe0
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 @@ -6,7 +6,47 @@
<title>{{ config('app.name') }} - API Docs</title>

<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, unescape(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 e80ffe0

Please sign in to comment.