π A self-hostable personal dashboard built for you. Includes status-checking, widgets, themes, icon packs, a UI editor and tons more!
Vue awesomedashboarddockerhomelabhomepagemitnodejsorganizationproductivitypwaself-hostedstartpagevue
π₯ Improved error coms for OIDC renewal failures (#2217)
Alicia Sykes3037c25a6afc
diff --git a/services/auth-oidc.js b/services/auth-oidc.jsindex b4dfc76e..e7ed82bc 100644--- a/services/auth-oidc.js+++ b/services/auth-oidc.js@@ -112,6 +112,9 @@ function deriveIsAdmin(claims, settings) {function createOidcMiddleware(settings, { permissive = false } = {}) {return async (req, res, next) => {const header = req.headers.authorization || '';+ if (/^Basic\s+/i.test(header)) {+ console.warn('[auth-oidc] expected Bearer token, received Basic auth header'); // eslint-disable-line no-console+ }const match = header.match(/^Bearer\s+(.+)$/i);if (!match) return next(); // No token attached, let downstream gates decideconst token = match[1].trim();diff --git a/src/utils/auth/KeycloakAuth.js b/src/utils/auth/KeycloakAuth.jsindex f83cc243..837e9ca9 100644--- a/src/utils/auth/KeycloakAuth.js+++ b/src/utils/auth/KeycloakAuth.js@@ -72,6 +72,17 @@ class KeycloakAuth {this.keycloakClient.logout();}+ async renewForApiRequest() {+ try {+ const refreshed = await this.keycloakClient.updateToken(30);+ if (refreshed) this.storeKeycloakInfo();+ return Boolean(getApiAuthHeader());+ } catch (err) {+ ErrorHandler('Keycloak token renewal failed', err);+ return false;+ }+ }+storeKeycloakInfo() {if (this.keycloakClient.tokenParsed && typeof this.keycloakClient.tokenParsed === 'object') {const {diff --git a/src/utils/auth/OidcAuth.js b/src/utils/auth/OidcAuth.jsindex 79fd8f89..645cd48e 100644--- a/src/utils/auth/OidcAuth.js+++ b/src/utils/auth/OidcAuth.js@@ -174,12 +174,36 @@ class OidcAuth {this.persistUserInfo(user);return true;}+ statusErrorMsg('OIDC', 'Silent renewal completed but no fresh id_token was issued; '+ + 'your provider may not reissue id_tokens on refresh.');} catch (err) {statusErrorMsg('OIDC', 'Silent token renewal failed, using interactive sign-in', err);}return false;}+ /* Called from request.js if we get a 401 back */+ async renewForApiRequest() {+ if (!this.silentRenewEnabled) {+ statusErrorMsg('OIDC', 'API request needs a fresh token, but silent renewal is disabled');+ return false;+ }+ const user = await this.userManager.getUser();+ if (!user) {+ statusErrorMsg('OIDC', 'API request was rejected and there is no active session to renew. Please sign in again.');+ return false;+ }+ if (!user.refresh_token) {+ statusErrorMsg(+ 'OIDC',+ 'API request needs a fresh token, but none is available. '+ + 'If this persists, ensure offline_access is granted, then sign in again.',+ );+ return false;+ }+ return this.trySilentRenew();+ }+/* Start OIDC background renewal for confirmed sessions if enabled */startBackgroundRenew(user) {if (this.silentRenewEnabled && user?.refresh_token) this.userManager.startSilentRenew();diff --git a/src/utils/auth/getApiAuthHeader.js b/src/utils/auth/getApiAuthHeader.jsindex ddcdc015..8662c0b3 100644--- a/src/utils/auth/getApiAuthHeader.js+++ b/src/utils/auth/getApiAuthHeader.js@@ -1,11 +1,9 @@/**- * Returns Authorization header for internal API requests when OIDC/KC configured- * Uses the id_token which is already stored locally after successful login+ * Auth for internal API requests when OIDC/Keycloak is configured.+ * Uses the id_token stashed in localStorage after a successful login.*- * Will return `null`, and cause the caller to fall through, when:- * - no token has been stashed- * - the stashed token can't be parsed- * - the token has already expired+ * `getApiAuthHeader()` returns the Bearer header, or null when the token is unusable.+ * `getApiAuthState()` returns { ok, reason, header? }, to say if/why token failed*/import { localStorageKeys } from '@/utils/config/defaults';@@ -17,27 +15,38 @@ function decodeBase64Url(input) {return atob(pad ? padded + '='.repeat(4 - pad) : padded);}-/* Check JWT isn't expired, the server will handle the actual verification */-function isExpired(token) {- try {- const [, payload] = token.split('.');- if (!payload) return true;- const claims = JSON.parse(decodeBase64Url(payload));- if (typeof claims.exp !== 'number') return false;- return claims.exp * 1000 <= Date.now();- } catch {- return true;- }+const tokenParts = (token) => (typeof token === 'string' ? token.split('.') : []);++function decodeClaims(token) {+ const [, payload] = tokenParts(token);+ if (!payload) throw new Error('Missing token payload');+ return JSON.parse(decodeBase64Url(payload));}-/* Returns { Authorization: 'Bearer β¦' } or null if no usable token is available */-export default function getApiAuthHeader() {+export function getApiAuthState() {let token;try {token = localStorage.getItem(localStorageKeys.ID_TOKEN);} catch {- return null;+ return { ok: false, reason: 'storage' };}- if (!token || isExpired(token)) return null;- return { Authorization: `Bearer ${token}` };+ if (!token) return { ok: false, reason: 'missing' };+ if (tokenParts(token).length === 5) return { ok: false, reason: 'encrypted-jwe' };+ if (tokenParts(token).length !== 3) return { ok: false, reason: 'malformed' };+ let claims;+ try {+ claims = decodeClaims(token);+ if (typeof claims.exp === 'number' && claims.exp * 1000 <= Date.now()) {+ return { ok: false, reason: 'expired' };+ }+ } catch {+ return { ok: false, reason: 'malformed' };+ }+ return { ok: true, reason: 'valid', header: { Authorization: `Bearer ${token}` } };+}++/* Returns { Authorization: 'Bearer...' } or null if no usable token */+export default function getApiAuthHeader() {+ const auth = getApiAuthState();+ return auth.ok ? auth.header : null;}diff --git a/src/utils/request.js b/src/utils/request.jsindex 822aa28a..8f6bb566 100644--- a/src/utils/request.js+++ b/src/utils/request.js@@ -8,7 +8,10 @@*/import { makeBasicAuthHeaders } from '@/utils/auth/Auth';-import getApiAuthHeader from '@/utils/auth/getApiAuthHeader';+import { getApiAuthState } from '@/utils/auth/getApiAuthHeader';+import { getOidcAuth, isOidcEnabled } from '@/utils/auth/OidcAuth';+import { getKeycloakAuth, isKeycloakEnabled } from '@/utils/auth/KeycloakAuth';+import { statusErrorMsg, statusMsg } from '@/utils/logging/CoolConsole';/** Check if a request URL targets the local Dashy server */function isLocalRequest(url) {@@ -19,6 +22,33 @@ function isLocalRequest(url) {return url.startsWith(origin) || (domain && url.startsWith(domain));}+function hasAuthorization(headers) {+ return Object.keys(headers).some((key) => key.toLowerCase() === 'authorization');+}++function ssoState() {+ return { oidc: isOidcEnabled(), keycloak: isKeycloakEnabled() };+}++/* Convert string key from backend into human issue of why bearer token failed */+function reportBearerIssue(reason) {+ if (reason === 'missing') return;+ const messages = {+ expired: 'SSO token expired.',+ malformed: 'SSO token is malformed; sign in again if renewal does not recover it.',+ 'encrypted-jwe': 'SSO token is encrypted. Dashy needs signed JWT tokens, not encrypted JWE tokens.',+ storage: 'SSO token could not be read from browser storage.',+ };+ statusErrorMsg('SSO', messages[reason] || `SSO token is not usable (${reason}).`);+}++/* Triggers OIDC session renewal to enabled provider (called if get 401) */+async function renewSsoSession({ oidc, keycloak }) {+ if (oidc) return getOidcAuth()?.renewForApiRequest?.() || false;+ if (keycloak) return getKeycloakAuth()?.renewForApiRequest?.() || false;+ return false;+}+class RequestError extends Error {constructor(message, opts = {}) {super(message);@@ -35,7 +65,7 @@ class RequestError extends Error {* @param {Object} config - { method, url, headers, data, timeout, params }* @returns {Promise<{data, status, statusText, headers}>}*/-async function makeRequest(config) {+async function makeRequest(config, retriedAfterRenew = false) {const {method = 'GET',url,@@ -67,10 +97,15 @@ async function makeRequest(config) {// For local API requests, attach auth headers when configured// Bearer (OIDC / Keycloak id_token) takes precedence over basic-auth cookie header- if (isLocalRequest(fullUrl) && !fetchOptions.headers.Authorization) {- const bearer = getApiAuthHeader();- if (bearer) {- Object.assign(fetchOptions.headers, bearer);+ const isLocal = isLocalRequest(fullUrl);+ const sso = isLocal ? ssoState() : null;++ if (isLocal && !hasAuthorization(fetchOptions.headers)) {+ const bearer = getApiAuthState();+ if (bearer.ok) {+ Object.assign(fetchOptions.headers, bearer.header);+ } else if (sso.oidc || sso.keycloak) {+ reportBearerIssue(bearer.reason);} else {const authConfig = makeBasicAuthHeaders();if (authConfig.headers) {@@ -111,6 +146,11 @@ async function makeRequest(config) {// Throw on non-2xx (matching axios behavior)if (!res.ok) {+ if (res.status === 401 && isLocal && !retriedAfterRenew && (sso.oidc || sso.keycloak)) {+ statusMsg('SSO', 'API request was unauthorized; attempting session renewal.');+ if (await renewSsoSession(sso)) return makeRequest(config, true);+ statusErrorMsg('SSO', 'Session renewal failed; reload or sign in again.');+ }throw new RequestError(`Request failed with status ${res.status}`,{ response },