From 6ff6aecb61a60860fedaa8dfed53d683b717d9ed Mon Sep 17 00:00:00 2001 From: Gerardo O Date: Mon, 31 Mar 2025 19:06:41 -0500 Subject: [PATCH] Enhance JWT handling with CSRF token support. - Introduced `csrfToken` variable to store the CSRF token. - Modified `fetchJWT` to extract and store CSRF token from the response. - Updated `refreshJWT` to include `X-CSRF-TOKEN` in headers when present. - Ensured consistent `Accept` and `Content-Type` headers for fetch requests. - Added `referrerPolicy: 'no-referrer-when-downgrade'` for improved compatibility. This improves security by ensuring CSRF protection for token refresh requests. --- resources/js/app.js | 28 +++++++++++++++++++++++----- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/resources/js/app.js b/resources/js/app.js index 233b4978..2a4c9434 100644 --- a/resources/js/app.js +++ b/resources/js/app.js @@ -56,6 +56,7 @@ window.GoAccess = window.GoAccess || { }; this.AppPrefs = GoAccess.Util.merge(this.AppPrefs, this.opts.prefs); this.currentJWT = null; + this.csrfToken = null; // WebSocket reconnection settings this.wsDelay = this.currDelay = 1E3; @@ -191,16 +192,33 @@ window.GoAccess = window.GoAccess || { fetchJWT: function (url) { return fetch(url, { method: 'GET', - credentials: 'include' - }).then(response => response.json()); + credentials: 'include', + headers: { 'Accept': 'application/json' }, + referrerPolicy: 'no-referrer-when-downgrade' + }) + .then(response => response.json()) + .then(data => { + if (data.status === 'success' && data.csrf_token) { + this.csrfToken = data.csrf_token; + } + return data; + }); }, refreshJWT: function (url, refreshToken) { + const headers = { + 'Accept': 'application/json', + 'Content-Type': 'application/json' + }; + if (this.csrfToken) { + headers['X-CSRF-TOKEN'] = this.csrfToken; + } return fetch(url, { method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ refresh_token: refreshToken }), - credentials: 'include' + credentials: 'include', + headers: headers, + referrerPolicy: 'no-referrer-when-downgrade', + body: JSON.stringify({ refresh_token: refreshToken }) }).then(response => response.json()); },