π A self-hostable personal dashboard built for you. Includes status-checking, widgets, themes, icon packs, a UI editor and tons more!
Vue awesomedashboarddockerhomelabhomepagemitnodejsorganizationproductivitypwaself-hostedstartpagevue
π Applies server-side authentication to all internal routes when OIDC/KC enabled
Alicia Sykes93f7633a7df3
diff --git a/docs/authentication.md b/docs/authentication.mdindex b3a56a7f..0bec846c 100644--- a/docs/authentication.md+++ b/docs/authentication.md@@ -30,7 +30,7 @@> [!IMPORTANT]> Dashy's built-in auth is not intended to protect a publicly hosted instance against unauthorized access. Instead you should use an auth provider compatible with your reverse proxy, or access Dashy via your VPN, or implement your own SSO logic.>-> If Dashy is only accessible within your home network and you just want a login page, then the built-in auth may be sufficient. To also protect server-side endpoints and config files, set `ENABLE_HTTP_AUTH=true` (see [Adding HTTP Auth to Configuration](#adding-http-auth-to-configuration)).+> If Dashy is only accessible within your home network and you just want a login page, then the built-in auth may be sufficient. To also protect server-side endpoints and config files: with built-in auth set `ENABLE_HTTP_AUTH=true` ([details](#adding-http-auth-to-configuration)). (Or, consider setting up[OIDC](#oidc), [Keycloak](#keycloak), or [Header Auth](#header-authentication), where the server-side enforcement is on automatically).## Built-In Auth@@ -210,11 +210,13 @@ Use the following run command, replacing the attributes (default credentials, podocker run -d \-p 8081:8080 \--name auth-server \- -e KEYCLOAK_USER=admin \- -e KEYCLOAK_PASSWORD=admin \- quay.io/keycloak/keycloak:15.0.2+ -e KEYCLOAK_ADMIN=admin \+ -e KEYCLOAK_ADMIN_PASSWORD=admin \+ quay.io/keycloak/keycloak:25.0 start-dev```+(The `KEYCLOAK_USER` / `KEYCLOAK_PASSWORD` env vars and the `/auth` URL prefix from Keycloak 16 and older have been replaced. If you are still on 17 or older, set `legacySupport: true` in your Dashy config later on.)+If you need to pull from DockerHub, a non-official image is available [here](https://registry.hub.docker.com/r/jboss/keycloak). Or if you would prefer not to use Docker, you can also directly install Keycloak from source, following [this guide](https://www.keycloak.org/docs/latest/getting_started/index.html).You should now be able to access the Keycloak web interface, using the port specified above (e.g. `http://127.0.0.1:8081`), login with the default credentials, and when prompted create a new password.@@ -230,14 +232,27 @@ Before we can use Keycloak, we must first set it up with some users. Keycloak usYou can now create your first user.1. In the left-hand menu, click 'Users', then 'Add User'-2. Fill in the form, including username and hit 'Save'+2. Fill in the form. On Keycloak 25 and newer, *First name* and *Last name* are required by the default user-profile schema. If you skip them the user can sign in but login will then fail with "Account is not fully set up"3. Under the 'Credentials' tab, give the new user an initial password. They will be prompted to change this after first login-The last thing we need to do in the Keycloak admin console is to create a new client+Next, create a new client for Dashy.1. Within your new realm, navigate to 'Clients' on the left-hand side, then click 'Create' in the top-right-2. Choose a 'Client ID', set 'Client Protocol' to 'openid-connect', and for 'Valid Redirect URIs' put a URL pattern to where you're hosting Dashy (if you're just testing locally, then * is fine), and do the same for the 'Web Origins' field-3. Make note of your client-id, and click 'Save'+2. Choose a 'Client ID' (e.g. `dashy`), set 'Client Protocol' to 'openid-connect'+3. Turn *Client authentication* OFF and leave *Standard flow* enabled. Dashy is a SPA, so it acts as an OAuth public client with PKCE. A confidential client requires a client_secret that a browser app can't safely hold+4. For 'Valid Redirect URIs' put the URL where you host Dashy (e.g. `https://dashy.example.com/*`, or just `*` while testing locally). Do the same for the 'Web Origins' field+5. Make note of your client-id, and click 'Save'++For the `adminRole` check to work, the role must appear in the id_token (Keycloak's default mapper only adds it to the access token):++1. Open your `dashy` client, go to the *Client scopes* tab, click the dedicated scope row (`dashy-dedicated`)+2. Add a new mapper of type *User Realm Role*, name it (e.g. `realm_roles`), claim name `realm_access.roles`, multivalued ON, *Add to ID token* ON, *Add to access token* ON+3. (Optional, for `adminGroup` instead of `adminRole`) Add a second mapper of type *Group Membership*, claim name `groups`++To create the admin role itself and grant it to a user:++1. *Realm roles* in the left-hand menu, *Create role*, name it (e.g. `dashy-admin`)+2. *Users* β pick your admin user β *Role mapping* β *Assign role* β select `dashy-admin`### 3. Enable Keycloak in Dashy Config File@@ -246,13 +261,15 @@ For example:```yamlappConfig:- ...+ # ...+ disableConfigurationForNonAdmin: trueauth:enableKeycloak: truekeycloak:serverUrl: 'http://localhost:8081'realm: 'alicia-homelab'clientId: 'dashy'+ adminRole: 'dashy-admin' # role name that grants admin privileges```Note that if you are using Keycloak V 17 or older, you will also need to set `legacySupport: true` (also under `appConfig.auth.keycloak`). This is because the API endpoint was updated in later versions.@@ -281,12 +298,19 @@ sections:groups: ['DevelopmentTeam']```-Depending on how you're hosting Dashy and Keycloak, you may also need to set some HTTP headers, to prevent a CORS error. This would typically be the `Access-Control-Allow-Origin [URL-of Dashy]` on your Keycloak instance. See the [Setting Headers](https://github.com/Lissy93/dashy/blob/master/docs/management.md#setting-headers) guide in the management docs for more info.-Your app is now secured :) When you load Dashy, it will redirect to your Keycloak login page, and any user without valid credentials will be prevented from accessing your dashboard.From within the Keycloak console, you can then configure things like time-outs, password policies, etc. You can also backup your full Keycloak config, and it is recommended to do this, along with your Dashy config. You can spin up both Dashy and Keycloak simultaneously and restore both applications configs using a `docker-compose.yml` file, and this is recommended.+### CORS Headers+If Dashy and Keycloak run on different origins (typical when testing locally on different `localhost:` ports), Keycloak's default `Content-Security-Policy: frame-ancestors 'self'` and `X-Frame-Options: SAMEORIGIN` block the hidden iframe `keycloak-js` uses to check your session. Symptom: a generic "Authentication failed (Keycloak)" toast on first load. To allow the iframe, open *Realm settings β Security defenses β Browser headers*, clear `X-Frame-Options`, and change `Content-Security-Policy` to `frame-src 'self' <your-dashy-origin>; frame-ancestors 'self' <your-dashy-origin>; object-src 'none';`. Same-origin production deployments don't hit this.++### How server-side enforcement works++Dashy's server reads `auth.keycloak` from `conf.yml` at boot, lazily fetches your Keycloak realm's OIDC discovery doc + JWKS, then verifies the `id_token` the SPA attaches to every API call as `Authorization: Bearer <id_token>`. Tokens that fail signature / issuer / audience / expiry verification are rejected with `401`. Write endpoints (`POST /config-manager/save`) additionally require the `adminRole` (or `adminGroup`) to be present in the token claims, and non-admins receive `403`. Note that the `/conf.yml` remains anonymously readable still (so the SPA can bootstrap before login).++The admin check reads the role / group claim from the id_token, so the client mapper from Step 2 above (the one with *Add to ID token* on) is what makes `adminRole` / `adminGroup` work. Without it the server gets a token with no roles claim and treats everyone as non-admin.+### Troubleshooting KeycloakIf you encounter issues with your Keycloak setup, follow these steps to troubleshoot and resolve common problems.@@ -357,6 +381,7 @@ Dashy also supports using a general [OIDC compatible](https://openid.net/connect```yamlappConfig:+ disableConfigurationForNonAdmin: true # Prevent authenticated non-admins using editorauth:enableOidc: trueoidc:@@ -368,6 +393,8 @@ appConfig:Because Dashy is a SPA, a [public client](https://datatracker.ietf.org/doc/html/rfc6749#section-2.1) registration with PKCE is needed.+If you set `adminGroup`, include `groups` in `scope` (e.g. `scope: 'openid profile email groups'`) so your IdP actually returns the claim in the id_token. Same goes for `adminRole` and a `roles` scope if your IdP needs one.+Note, that if your `clientId` is numeric, you must place it in quotes. Otherwise it will be interpreted as a number and truncated to 64 chars!An example for Authelia is shared below, but other OIDC systems can be used:@@ -396,6 +423,12 @@ identity_providers:Groups and roles will be populated and available for controlling display similar to [Keycloak](#Keycloak) above.+### How server-side enforcement works++Dashy's server reads `auth.oidc` from `conf.yml` at boot, lazily fetches the OIDC discovery doc + JWKS from your `endpoint`, then verifies the `id_token` the SPA attaches to every API call as `Authorization: Bearer <id_token>`. Tokens that fail signature / issuer / audience / expiry verification are rejected with `401`. Write endpoints (`POST /config-manager/save`) additionally require the `adminGroup` (or `adminRole`) to be present in the token's `groups` / `roles` claims, and non-admins receive `403`. Note that the `/conf.yml` remains anonymously readable still++Your IdP must include `groups` / `roles` in the id_token, not only the access token, for the admin check to work (most IdPs do this when the `groups` scope is requested).+---## authentik@@ -433,7 +466,7 @@ A dialog box will pop-up, select the `OAuth2/OpenID Provider`. Click `Next`.-On the next page of the wizard, set the `Name`, `Authentication flow`, and `Authorization flow`. See example below. Using the `default-provider-authorization-implicit-consent` authorization flow on internal services and `default-provider-authorization-explicit-consent` on external services is a common practice. However, it is fully up to you on how you would like to configure this option. `Implicit` will login directly without user consent, `explicit` will ask if the user approves the service being logged into with their user credentials.+On the next page of the wizard, set the `Name`, `Authentication flow`, `Authorization flow`, and `Invalidation flow`. See example below. Using the `default-provider-authorization-implicit-consent` authorization flow on internal services and `default-provider-authorization-explicit-consent` on external services is a common practice. However, it is fully up to you on how you would like to configure this option. `Implicit` will login directly without user consent, `explicit` will ask if the user approves the service being logged into with their user credentials. For the invalidation flow (required on Authentik 2023.10 and later) the built-in `default-provider-invalidation-flow` is fine.@@ -448,7 +481,15 @@ Scroll down to set the `Signing Key`. It is recommended to use the built in `aut-Expand `Advanced protocol settings` then verify the `Scopes` are set to what is highlighted in `white` below. Set the `Subject mode` to `Based on the Users's Email`.+If you plan to use `adminGroup` in your Dashy config, you need a `groups` scope mapping first. Authentik does not ship one by default. Open *Customisation > Property Mappings* in a new tab, click *Create > Scope Mapping*, set *Name* to `groups`, *Scope name* to `groups`, and *Expression* to:++```python+return {"groups": [g.name for g in request.user.ak_groups.all()]}+```++Save it, then come back to the provider wizard.++Expand `Advanced protocol settings` then verify the `Scopes` are set to what is highlighted in `white` below (including the `groups` mapping you just created, if you want `adminGroup` to work). Set the `Subject mode` to `Based on the Users's Email`.@@ -507,11 +548,12 @@ Enter the `Client ID` in the `clientId` field and `OpenID Configuration Issuer`Below is how to configure the `auth` section in the yaml syntax. Once this is enabled, when an attempt to access `Dashy` is made it will now redirect you to the `authentik` login page moving forward.-```+```yamlappConfig:theme: glasslayout: autoiconSize: medium+ disableConfigurationForNonAdmin: true # Prevent logged-in, non-admins using the view/edit config featuresauth:enableOidc: trueoidc:diff --git a/docs/troubleshooting.md b/docs/troubleshooting.mdindex b8c6e101..1c67e2f5 100644--- a/docs/troubleshooting.md+++ b/docs/troubleshooting.md@@ -175,7 +175,7 @@ docker compose up -d --force-recreate### Intentionally read-only mode-To stop anyone saving from the UI, set `appConfig.preventWriteToDisk: true` in `conf.yml`. This disables the endpoint and the save button. For Docker users, you can harden things further, by mounting the config and all user-data as read-only.+To hide the "Save to disk" UI for everyone, set `appConfig.preventWriteToDisk: true` in `conf.yml`. This is a UI-only flag β the `/config-manager/save` server endpoint itself is gated by the configured auth method (`auth.users` with `ENABLE_HTTP_AUTH`, OIDC/Keycloak admin role, header-auth, etc.), so anyone unauthenticated or non-admin already can't save regardless of this flag. For Docker users, you can harden things further by mounting `user-data` (or just `conf.yml`) as read-only β the kernel will refuse the write even before the server tries.---diff --git a/package.json b/package.jsonindex 1f70d03a..c9705f87 100644--- a/package.json+++ b/package.json@@ -41,6 +41,7 @@"express": "^4.21.0","express-basic-auth": "^1.2.1","frappe-charts": "^1.6.2",+ "jose": "^5.10.0","js-yaml": "^4.1.0","keycloak-js": "^26.0.0","oidc-client-ts": "^3.0.1",diff --git a/services/app.js b/services/app.jsindex dd2b1023..da68f39e 100644--- a/services/app.js+++ b/services/app.js@@ -30,6 +30,7 @@ const systemInfo = require('./system-info'); // Basic system info, for resourceconst sslServer = require('./ssl-server'); // TLS-enabled web serverconst corsProxy = require('./cors-proxy'); // Enables API requests to CORS-blocked servicesconst getUser = require('./get-user'); // Enables server side user lookup+const { loadOidcSettings, createOidcMiddleware } = require('./auth-oidc'); // Server-side OIDC/Keycloak token verification/* Service endpoint URL paths (see also serviceEndpoints in src/utils/config/defaults.js) */const ENDPOINTS = {@@ -78,7 +79,7 @@ process.on('unhandledRejection', (reason) => {/* Load appConfig.auth from config (if present) for authorization purposes */function loadAuthConfig() {try {- const filePath = path.join(rootDir, process.env.USER_DATA_DIR || 'user-data', 'conf.yml');+ const filePath = path.resolve(rootDir, process.env.USER_DATA_DIR || 'user-data', 'conf.yml');const fileContents = fs.readFileSync(filePath, 'utf8');const data = yaml.load(fileContents);return data?.appConfig?.auth || {};@@ -116,9 +117,9 @@ function customAuthorizer(username, password) {}}-/* If auth is enabled, setup auth for config access, otherwise skip */-function getBasicAuthMiddleware() {- const authConfig = loadAuthConfig();+/* Pick an auth strategy based on what's configured in conf.yml + env.+ OIDC / Keycloak takes precedence β it's the strongest enforcement we offer. */+function getAuthMiddleware(authConfig, oidcSettings) {const confUsers = authConfig.users || null;const hasConfUsers = confUsers && confUsers.length > 0;const useConfAuth = process.env.ENABLE_HTTP_AUTH && hasConfUsers;@@ -133,7 +134,9 @@ function getBasicAuthMiddleware() {+ ' This will cause auth failures. Set ENABLE_HTTP_AUTH=true, or remove users from conf.yml.');}- if (useConfAuth) {+ if (oidcSettings) {+ return createOidcMiddleware(oidcSettings);+ } else if (useConfAuth) {return basicAuth({authorizer: customAuthorizer,challenge: true,@@ -163,11 +166,37 @@ function getBasicAuthMiddleware() {return (req, res, next) => next();}-const protectConfig = getBasicAuthMiddleware();+const initialAuthConfig = loadAuthConfig();+const oidcSettings = loadOidcSettings(initialAuthConfig);+const protectConfig = getAuthMiddleware(initialAuthConfig, oidcSettings);-/* Middleware to restrict write endpoints to admin users only */+/* True when any auth method is configured. Used to keep zero-auth deployments+ open (their original behaviour) while closing the gate for everyone else. */+const authIsConfigured = Boolean(+ oidcSettings+ || (process.env.ENABLE_HTTP_AUTH && initialAuthConfig.users?.length)+ || (process.env.BASIC_AUTH_USERNAME && process.env.BASIC_AUTH_PASSWORD)+ || (initialAuthConfig.enableHeaderAuth && initialAuthConfig.headerAuth),+);++/* Require an authenticated identity on this request. No-op for zero-auth deploys. */+function requireAuth(req, res, next) {+ if (!authIsConfigured) return next();+ if (req.auth) return next();+ return res.status(401).json({ success: false, message: 'Unauthorized' });+}++/* Restrict to admin users. OIDC/Keycloak get isAdmin from token claims; the+ conf.yml `users[]` path falls back to looking up user.type === 'admin'. */function requireAdmin(req, res, next) {- if (!req.auth) return next();+ if (!authIsConfigured) return next();+ if (!req.auth) {+ return res.status(401).json({ success: false, message: 'Unauthorized' });+ }+ if (typeof req.auth.isAdmin === 'boolean') {+ if (req.auth.isAdmin) return next();+ return res.status(403).json({ success: false, message: 'Forbidden - Admin access required' });+ }const users = loadUserConfig();if (!users || users.length === 0) return next();const user = users.find(u => u.user.toLowerCase() === req.auth.user.toLowerCase());@@ -191,7 +220,7 @@ const app = express()// Load middlewares for parsing JSON, and supporting HTML5 history routing.use(express.json({ limit: '1mb' }))// GET endpoint to run status of a given URL with GET request- .use(ENDPOINTS.statusCheck, protectConfig, method('GET', (req, res) => {+ .use(ENDPOINTS.statusCheck, protectConfig, requireAuth, method('GET', (req, res) => {try {statusCheck(req.url, (results) => {if (!res.headersSent) {@@ -223,7 +252,7 @@ const app = express()});}))// GET endpoint to return system info, for widget- .use(ENDPOINTS.systemInfo, protectConfig, method('GET', (req, res) => {+ .use(ENDPOINTS.systemInfo, protectConfig, requireAuth, method('GET', (req, res) => {try {safeEnd(res, JSON.stringify(systemInfo()));} catch (e) {@@ -231,7 +260,7 @@ const app = express()}}))// GET for accessing non-CORS API services- .use(ENDPOINTS.corsProxy, protectConfig, (req, res) => {+ .use(ENDPOINTS.corsProxy, protectConfig, requireAuth, (req, res) => {try {corsProxy(req, res);} catch (e) {@@ -239,7 +268,7 @@ const app = express()}})// GET endpoint to return user info- .use(ENDPOINTS.getUser, protectConfig, method('GET', (req, res) => {+ .use(ENDPOINTS.getUser, protectConfig, requireAuth, method('GET', (req, res) => {try {safeEnd(res, JSON.stringify(getUser(config, req)));} catch (e) {@@ -249,13 +278,13 @@ const app = express()// Middleware to serve any .yml files in USER_DATA_DIR with optional protection.get('/*.yml', protectConfig, (req, res) => {const ymlFile = req.path.split('/').pop();- const filePath = path.join(rootDir, process.env.USER_DATA_DIR || 'user-data', ymlFile);+ const filePath = path.resolve(rootDir, process.env.USER_DATA_DIR || 'user-data', ymlFile);res.sendFile(filePath, (err) => {if (err) safeEnd(res, errBody(`Could not read ${ymlFile}`), 404);});})// Serves up static files- .use(express.static(path.join(rootDir, process.env.USER_DATA_DIR || 'user-data')))+ .use(express.static(path.resolve(rootDir, process.env.USER_DATA_DIR || 'user-data'))).use(express.static(path.join(rootDir, 'dist'))).use(express.static(path.join(rootDir, 'public'), { index: 'initialization.html' }))// If no other route is matched, serve up the index.html with a 404 statusdiff --git a/services/auth-oidc.js b/services/auth-oidc.jsnew file mode 100644index 00000000..c41747af--- /dev/null+++ b/services/auth-oidc.js@@ -0,0 +1,140 @@+/**+ * Server-side OIDC / Keycloak token verification.+ *+ * Why this exists: Dashy's OIDC + Keycloak flows are otherwise entirely+ * client-side, so the server never sees an identity. This module verifies the+ * id_token a logged-in browser attaches to API requests, so admin-gated+ * endpoints (and authenticated endpoints generally) can enforce auth server-side.+ *+ * The middleware is permissive on a missing Authorization header β bootstrap+ * fetches (e.g. /conf.yml) must succeed before the user is logged in. Endpoints+ * that require auth should be paired with `requireAuth` (in app.js).+ * A present-but-invalid token is always rejected.+ */++const { createRemoteJWKSet, jwtVerify } = require('jose');++/* Normalise the OIDC / Keycloak block from conf.yml into a unified shape.+ Returns null when neither provider is enabled or required fields are missing. */+function loadOidcSettings(authConfig) {+ if (!authConfig || typeof authConfig !== 'object') return null;++ if (authConfig.enableOidc && authConfig.oidc) {+ const { endpoint, clientId, adminGroup, adminRole } = authConfig.oidc;+ if (!endpoint || !clientId) return null;+ return {+ kind: 'oidc',+ issuer: String(endpoint),+ clientId: String(clientId),+ adminGroup: adminGroup || null,+ adminRole: adminRole || null,+ };+ }++ if (authConfig.enableKeycloak && authConfig.keycloak) {+ const {+ serverUrl, realm, clientId, adminGroup, adminRole, legacySupport,+ } = authConfig.keycloak;+ if (!serverUrl || !realm || !clientId) return null;+ // Mirror the URL keycloak-js builds in the browser.+ const base = (legacySupport ? `${serverUrl}/auth` : serverUrl).replace(/\/$/, '');+ return {+ kind: 'keycloak',+ issuer: `${base}/realms/${realm}`,+ clientId: String(clientId),+ adminGroup: adminGroup || null,+ adminRole: adminRole || null,+ };+ }++ return null;+}++/* Per-issuer cache: discovery metadata + JWKS resolver. createRemoteJWKSet+ handles key caching + rotation internally. */+const issuerCache = new Map();++async function fetchDiscovery(issuer) {+ const base = issuer.endsWith('/') ? issuer : `${issuer}/`;+ const url = new URL('.well-known/openid-configuration', base);+ const res = await fetch(url);+ if (!res.ok) throw new Error(`OIDC discovery returned ${res.status} for ${url}`);+ return res.json();+}++async function getIssuerContext(issuer) {+ const cached = issuerCache.get(issuer);+ if (cached) return cached;+ const config = await fetchDiscovery(issuer);+ if (!config.issuer || !config.jwks_uri) {+ throw new Error('Discovery document is missing `issuer` or `jwks_uri`');+ }+ const ctx = {+ canonicalIssuer: config.issuer,+ jwks: createRemoteJWKSet(new URL(config.jwks_uri)),+ };+ issuerCache.set(issuer, ctx);+ return ctx;+}++/* Pure helper: true when the token's claims map to the configured admin group/role.+ Handles standard OIDC top-level `groups`/`roles` claims plus Keycloak's nested+ realm_access / resource_access role shapes (mirrors what KeycloakAuth.js does+ client-side). */+function deriveIsAdmin(claims, settings) {+ if (!claims) return false;+ const groups = Array.isArray(claims.groups) ? [...claims.groups] : [];+ const roles = Array.isArray(claims.roles) ? [...claims.roles] : [];++ if (settings.kind === 'keycloak') {+ const realmRoles = claims.realm_access && claims.realm_access.roles;+ if (Array.isArray(realmRoles)) roles.push(...realmRoles);+ const clientRoles = claims.resource_access+ && claims.resource_access[settings.clientId]+ && claims.resource_access[settings.clientId].roles;+ if (Array.isArray(clientRoles)) roles.push(...clientRoles);+ }++ const { adminGroup, adminRole } = settings;+ if (adminGroup && groups.includes(adminGroup)) return true;+ if (adminRole && roles.includes(adminRole)) return true;+ return false;+}++/* Connect middleware factory. Verifies Bearer id_token; sets req.auth on success. */+function createOidcMiddleware(settings) {+ return async (req, res, next) => {+ const header = req.headers.authorization || '';+ const match = header.match(/^Bearer\s+(.+)$/i);+ if (!match) return next(); // Permissive: no token attached, let downstream gates decide+ const token = match[1].trim();+ if (!token) return next();++ try {+ const { canonicalIssuer, jwks } = await getIssuerContext(settings.issuer);+ const { payload } = await jwtVerify(token, jwks, {+ issuer: canonicalIssuer,+ audience: settings.clientId,+ clockTolerance: '30s',+ });+ req.auth = {+ user: payload.preferred_username || payload.email || payload.sub || 'unknown',+ isAdmin: deriveIsAdmin(payload, settings),+ claims: payload,+ };+ return next();+ } catch (e) {+ console.warn('[auth-oidc] token verification failed:', e.message || e); // eslint-disable-line no-console+ return res.status(401).json({+ success: false,+ message: 'Unauthorized - Invalid or expired token',+ });+ }+ };+}++module.exports = {+ loadOidcSettings,+ createOidcMiddleware,+ deriveIsAdmin,+};diff --git a/src/router.js b/src/router.jsindex c24f243d..2c9ca4e5 100644--- a/src/router.js+++ b/src/router.js@@ -18,15 +18,21 @@ import Keys from '@/utils/StoreMutations';import { isAuthEnabled, isLoggedIn, isGuestAccessEnabled } from '@/utils/auth/Auth';import { isOidcEnabled } from '@/utils/auth/OidcAuth';import { isKeycloakEnabled } from '@/utils/auth/KeycloakAuth';+import { isHeaderAuthEnabled } from '@/utils/auth/HeaderAuth';import { startingView as defaultStartingView, routePaths } from '@/utils/config/defaults';import { VIEW_META } from '@/utils/config/ConfigHelpers';import ErrorHandler from '@/utils/logging/ErrorHandler';const progress = new Progress({ color: 'var(--progress-bar)' });+/* True for ANY auth (OIDC, KC, HeaderAuth, etc) */+const isAnyAuthConfigured = () =>+ isAuthEnabled() || isOidcEnabled() || isKeycloakEnabled() || isHeaderAuthEnabled();+/* Returns true if user is already authenticated, or if auth is not enabled */const isAuthenticated = () => {- const authEnabled = isAuthEnabled();+ if (store.state.criticalError) return false;+ const authEnabled = isAnyAuthConfigured();const userLoggedIn = isLoggedIn();const guestEnabled = isGuestAccessEnabled();return (!authEnabled || userLoggedIn || guestEnabled);diff --git a/src/utils/auth/Auth.js b/src/utils/auth/Auth.jsindex 9ab9a348..d517e8b4 100644--- a/src/utils/auth/Auth.js+++ b/src/utils/auth/Auth.js@@ -33,14 +33,11 @@ const getUsers = () => {// Otherwise, return the users array, if availableconst users = auth.users ? [...auth.users] : [];- if (isOidcEnabled()) {- if (localStorage[localStorageKeys.USERNAME]) {- const user = {- user: localStorage[localStorageKeys.USERNAME],- type: localStorage[localStorageKeys.ISADMIN] === 'true' ? 'admin' : 'normal',- };- users.push(user);- }+ if ((isOidcEnabled() || isKeycloakEnabled()) && localStorage[localStorageKeys.USERNAME]) {+ users.push({+ user: localStorage[localStorageKeys.USERNAME],+ type: localStorage[localStorageKeys.ISADMIN] === 'true' ? 'admin' : 'normal',+ });}return users;@@ -91,7 +88,7 @@ export const isLoggedIn = () => {const users = getUsers();const cookieToken = getCookieToken();- if (isOidcEnabled()) {+ if (isOidcEnabled() || isKeycloakEnabled()) {const username = localStorage[localStorageKeys.USERNAME]; // Get usernameif (!username) return false; // No usernamereturn users.some((user) => (diff --git a/src/utils/auth/KeycloakAuth.js b/src/utils/auth/KeycloakAuth.jsindex 2dcfd86f..99492ac8 100644--- a/src/utils/auth/KeycloakAuth.js+++ b/src/utils/auth/KeycloakAuth.js@@ -17,8 +17,10 @@ class KeycloakAuth {constructor(Keycloak) {const { auth } = getAppConfig();const {- serverUrl, realm, clientId, idpHint, legacySupport,+ serverUrl, realm, clientId, idpHint, legacySupport, adminGroup, adminRole,} = auth.keycloak;+ this.adminGroup = adminGroup;+ this.adminRole = adminRole;if (typeof clientId === 'number' && !Number.isSafeInteger(clientId)) {ErrorHandler('Keycloak clientId appears invalid. ',@@ -31,12 +33,12 @@ class KeycloakAuth {const loginOptions = idpHint ? { idpHint } : {};this.loginOptions = loginOptions;- this.keycloakClient = Keycloak(initOptions);+ this.keycloakClient = new Keycloak(initOptions);}login() {return new Promise((resolve, reject) => {- this.keycloakClient.init({ onLoad: 'check-sso' })+ this.keycloakClient.init({ onLoad: 'check-sso', responseMode: 'query' }).then((auth) => {if (auth) {this.storeKeycloakInfo();@@ -55,6 +57,8 @@ class KeycloakAuth {logout() {localStorage.removeItem(localStorageKeys.USERNAME);localStorage.removeItem(localStorageKeys.KEYCLOAK_INFO);+ localStorage.removeItem(localStorageKeys.ISADMIN);+ localStorage.removeItem(localStorageKeys.ID_TOKEN);this.keycloakClient.logout();}@@ -68,10 +72,10 @@ class KeycloakAuth {preferred_username: preferredUsername,} = this.keycloakClient.tokenParsed;- const realmRoles = realmAccess.roles || [];+ const realmRoles = (realmAccess && realmAccess.roles) || [];let clientRoles = [];- if (Object.hasOwn(resourceAccess, clientId)) {+ if (resourceAccess && Object.hasOwn(resourceAccess, clientId)) {clientRoles = resourceAccess[clientId].roles || [];}@@ -82,8 +86,18 @@ class KeycloakAuth {roles,};+ // Compute isAdmin from the configured admin group/role+ const isAdmin = (Array.isArray(groups) && this.adminGroup && groups.includes(this.adminGroup))+ || (Array.isArray(roles) && this.adminRole && roles.includes(this.adminRole))+ || false;+localStorage.setItem(localStorageKeys.KEYCLOAK_INFO, JSON.stringify(info));localStorage.setItem(localStorageKeys.USERNAME, preferredUsername);+ localStorage.setItem(localStorageKeys.ISADMIN, isAdmin);+ // Save id_token locally, so it can be attached as Bearer for network requests+ if (this.keycloakClient.idToken) {+ localStorage.setItem(localStorageKeys.ID_TOKEN, this.keycloakClient.idToken);+ }}}}diff --git a/src/utils/auth/OidcAuth.js b/src/utils/auth/OidcAuth.jsindex 77234bcb..48fbe118 100644--- a/src/utils/auth/OidcAuth.js+++ b/src/utils/auth/OidcAuth.js@@ -53,39 +53,43 @@ class OidcAuth {const code = url.searchParams.get('code');if (code) {- await this.userManager.signinCallback(window.location.href);+ // Populate localStorage before the reload so the post-reload route guard+ // sees the user as logged-in and lets them through to /, not /login.+ const callbackUser = await this.userManager.signinCallback(window.location.href);+ if (callbackUser) this.persistUserInfo(callbackUser);window.location.href = '/';return;}const user = await this.userManager.getUser();-if (user === null) {if (!isOidcGuestAccessEnabled()) {await this.userManager.signinRedirect();}} else {- const { roles = [], groups = [] } = user.profile;- const info = {- groups,- roles,- };- const isAdmin = (Array.isArray(groups) && groups.includes(this.adminGroup))- || (Array.isArray(roles) && roles.includes(this.adminRole))- || false;-- statusMsg(`user: ${user.profile.preferred_username} admin: ${isAdmin}`, JSON.stringify(info));-- localStorage.setItem(localStorageKeys.KEYCLOAK_INFO, JSON.stringify(info));- localStorage.setItem(localStorageKeys.USERNAME, user.profile.preferred_username);- localStorage.setItem(localStorageKeys.ISADMIN, isAdmin);+ this.persistUserInfo(user);}}+ /* Mirror the OIDC user into the localStorage keys other parts of Dashy read */+ persistUserInfo(user) {+ const { roles = [], groups = [] } = user.profile;+ const info = { groups, roles };+ const isAdmin = (Array.isArray(groups) && groups.includes(this.adminGroup))+ || (Array.isArray(roles) && roles.includes(this.adminRole))+ || false;+ statusMsg(`user: ${user.profile.preferred_username} admin: ${isAdmin}`, JSON.stringify(info));+ localStorage.setItem(localStorageKeys.KEYCLOAK_INFO, JSON.stringify(info));+ localStorage.setItem(localStorageKeys.USERNAME, user.profile.preferred_username);+ localStorage.setItem(localStorageKeys.ISADMIN, isAdmin);+ if (user.id_token) localStorage.setItem(localStorageKeys.ID_TOKEN, user.id_token);+ }+async logout() {localStorage.removeItem(localStorageKeys.USERNAME);localStorage.removeItem(localStorageKeys.KEYCLOAK_INFO);localStorage.removeItem(localStorageKeys.ISADMIN);+ localStorage.removeItem(localStorageKeys.ID_TOKEN);try {await this.userManager.signoutRedirect();diff --git a/src/utils/auth/getApiAuthHeader.js b/src/utils/auth/getApiAuthHeader.jsnew file mode 100644index 00000000..ddcdc015--- /dev/null+++ b/src/utils/auth/getApiAuthHeader.js@@ -0,0 +1,43 @@+/**+ * Returns Authorization header for internal API requests when OIDC/KC configured+ * Uses the id_token which is already stored locally after 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+ */++import { localStorageKeys } from '@/utils/config/defaults';++/* Base64URL β utf-8 string decode */+function decodeBase64Url(input) {+ const padded = input.replace(/-/g, '+').replace(/_/g, '/');+ const pad = padded.length % 4;+ 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;+ }+}++/* Returns { Authorization: 'Bearer β¦' } or null if no usable token is available */+export default function getApiAuthHeader() {+ let token;+ try {+ token = localStorage.getItem(localStorageKeys.ID_TOKEN);+ } catch {+ return null;+ }+ if (!token || isExpired(token)) return null;+ return { Authorization: `Bearer ${token}` };+}diff --git a/src/utils/config/ConfigSchema.json b/src/utils/config/ConfigSchema.jsonindex c00c9f28..8215c20e 100644--- a/src/utils/config/ConfigSchema.json+++ b/src/utils/config/ConfigSchema.json@@ -694,6 +694,16 @@"type": "string","description": "Set to the 'Alias' of an existing Identity Provider in the specified realm to skip the Keycloak login page and redirect straight to the external IdP for authentication"},+ "adminRole": {+ "title": "Admin Role",+ "type": "string",+ "description": "The realm or client role that grants admin privileges (mapped into realm_access.roles in the id_token). If not set, no roles will be considered admin."+ },+ "adminGroup": {+ "title": "Admin Group",+ "type": "string",+ "description": "The group claim value that grants admin privileges. Requires a Keycloak mapper that puts a 'groups' claim into the id_token. If not set, no groups will be considered admin."+ },"legacySupport": {"title": "Legacy Support","type": "boolean",diff --git a/src/utils/config/defaults.js b/src/utils/config/defaults.jsindex bfee1a15..fe437354 100644--- a/src/utils/config/defaults.js+++ b/src/utils/config/defaults.js@@ -145,6 +145,7 @@ const defaults = {LAST_USED: 'lastUsed',KEYCLOAK_INFO: 'keycloakInfo',ISADMIN: 'isAdmin',+ ID_TOKEN: 'idToken',DISABLE_CRITICAL_WARNING: 'disableCriticalWarning',},/* Key names for cookie identifiers */diff --git a/src/utils/request.js b/src/utils/request.jsindex 550c8380..822aa28a 100644--- a/src/utils/request.js+++ b/src/utils/request.js@@ -8,6 +8,7 @@*/import { makeBasicAuthHeaders } from '@/utils/auth/Auth';+import getApiAuthHeader from '@/utils/auth/getApiAuthHeader';/** Check if a request URL targets the local Dashy server */function isLocalRequest(url) {@@ -64,11 +65,17 @@ async function makeRequest(config) {signal: controller.signal,};- // For local API requests, include basic auth headers when configured+ // For local API requests, attach auth headers when configured+ // Bearer (OIDC / Keycloak id_token) takes precedence over basic-auth cookie headerif (isLocalRequest(fullUrl) && !fetchOptions.headers.Authorization) {- const authConfig = makeBasicAuthHeaders();- if (authConfig.headers) {- Object.assign(fetchOptions.headers, authConfig.headers);+ const bearer = getApiAuthHeader();+ if (bearer) {+ Object.assign(fetchOptions.headers, bearer);+ } else {+ const authConfig = makeBasicAuthHeaders();+ if (authConfig.headers) {+ Object.assign(fetchOptions.headers, authConfig.headers);+ }}}diff --git a/tests/server/cors-proxy.test.js b/tests/server/cors-proxy.test.jsindex 19b772e4..d86f3f93 100644--- a/tests/server/cors-proxy.test.js+++ b/tests/server/cors-proxy.test.js@@ -1,10 +1,18 @@// @vitest-environment nodeimport http from 'http';+import fs from 'fs';+import os from 'os';+import path from 'path';import {describe, it, expect, afterEach, beforeAll, afterAll, vi,} from 'vitest';import request from 'supertest';+// Isolate from the repo's conf.yml so test behaviour doesn't depend on which+// auth method (if any) the developer has configured locally.+const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'dashy-cors-test-'));+process.env.USER_DATA_DIR = tmpDir;+const app = require('../../services/app');const { substituteEnv } = require('../../services/cors-proxy');diff --git a/tests/server/general.test.js b/tests/server/general.test.jsindex 56f82e93..35adf65b 100644--- a/tests/server/general.test.js+++ b/tests/server/general.test.js@@ -1,7 +1,16 @@// @vitest-environment node+import fs from 'fs';+import os from 'os';+import path from 'path';import { describe, it, expect } from 'vitest';import request from 'supertest';+// Isolate from the repo's conf.yml so test behaviour doesn't depend on which+// auth method (if any) the developer has configured locally.+const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'dashy-general-test-'));+fs.writeFileSync(path.join(tmpDir, 'conf.yml'), 'pageInfo:\n title: Test\nsections: []\n');+process.env.USER_DATA_DIR = tmpDir;+const app = require('../../services/app');describe('Healthcheck', () => {diff --git a/tests/server/status-check.test.js b/tests/server/status-check.test.jsindex 6a18a583..da9ea748 100644--- a/tests/server/status-check.test.js+++ b/tests/server/status-check.test.js@@ -1,7 +1,13 @@// @vitest-environment node+import fs from 'fs';+import os from 'os';+import path from 'path';import { describe, it, expect } from 'vitest';import request from 'supertest';+const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'dashy-status-test-'));+process.env.USER_DATA_DIR = tmpDir;+const app = require('../../services/app');describe('Status check', () => {diff --git a/yarn.lock b/yarn.lockindex 416c8d4b..0830a8a4 100644--- a/yarn.lock+++ b/yarn.lock@@ -3803,6 +3803,11 @@ jake@^10.8.5:filelist "^1.0.4"picocolors "^1.1.1"+jose@^5.10.0:+ version "5.10.0"+ resolved "https://registry.yarnpkg.com/jose/-/jose-5.10.0.tgz#c37346a099d6467c401351a9a0c2161e0f52c4be"+ integrity sha512-s+3Al/p9g32Iq+oqXxkW//7jk2Vig6FF1CFqzVXoTUXt2qz89YWbL+OwS17NFYEvxC35n0FKeGO2LGYSxeM2Gg==+js-beautify@^1.14.9:version "1.15.4"resolved "https://registry.yarnpkg.com/js-beautify/-/js-beautify-1.15.4.tgz#f579f977ed4c930cef73af8f98f3f0a608acd51e"