### Install Nuxt Keycloak Module Source: https://github.com/productdevbook/nuxt-keycloak/blob/main/README.md This snippet shows how to install the nuxt-keycloak module using different package managers (pnpm, npm, yarn). This is the first step in integrating Keycloak authentication into a Nuxt application. ```bash pnpm add nuxt-keycloak # or npm install nuxt-keycloak # or yarn add nuxt-keycloak ``` -------------------------------- ### Basic Authentication with useKeycloak Composable Source: https://github.com/productdevbook/nuxt-keycloak/blob/main/README.md This Vue component example shows how to use the `useKeycloak()` composable to manage basic authentication. It demonstrates checking authentication status, displaying user information, and providing login/logout buttons. ```vue ``` -------------------------------- ### Local Development Commands for Nuxt Keycloak Source: https://github.com/productdevbook/nuxt-keycloak/blob/main/README.md A set of bash commands to manage the development environment for the Nuxt Keycloak project. This includes installing dependencies, preparing type stubs, running the development server, building the playground, linting, testing, and releasing new versions. ```bash # Install dependencies pnpm install # Generate type stubs pnpm run dev:prepare # Develop with the playground pnpm run dev # Build the playground pnpm run dev:build # Run ESLint pnpm run lint # Run Vitest pnpm run test pnpm run test:watch # Release new version pnpm run release ``` -------------------------------- ### Nuxt Keycloak Server API Example Source: https://context7.com/productdevbook/nuxt-keycloak/llms.txt Demonstrates how to use various server utilities from 'nuxt-keycloak/server' to handle authentication, token verification, and role checks in a Nuxt.js API route. It covers extracting tokens, verifying them, accessing user information, and enforcing authorization rules. ```typescript // server/api/utilities-demo.ts // All functions are auto-imported, but can also be explicitly imported: // import { // verifyKeycloakToken, // extractToken, // getKeycloakUser, // getKeycloakToken, // isAuthenticated, // hasRealmRole, // hasResourceRole, // requireKeycloakAuth, // requireRealmRole, // requireResourceRole, // decodeKeycloakToken // } from 'nuxt-keycloak/server' export default defineEventHandler(async (event) => { // 1. Extract token from Authorization: Bearer header const token = extractToken(event) // Returns: string | null // 2. Verify and decode token (uses JWKS or decode based on config) const user = await verifyKeycloakToken(token) // Returns: KeycloakTokenParsed | null // Token structure: { sub, preferred_username, email, realm_access, resource_access, exp, iat, ... } // 3. Decode token without verification (manual usage) const decoded = decodeKeycloakToken(token) // Returns: KeycloakTokenParsed | null // Use only when token is pre-verified by trusted system // 4. Get user from request context (set by middleware or manually) const contextUser = getKeycloakUser(event) // Returns: KeycloakTokenParsed | null // 5. Get token from request context const contextToken = getKeycloakToken(event) // Returns: string | null // 6. Check if request is authenticated const authenticated = isAuthenticated(event) // Returns: boolean // 7. Check if user has specific realm role const hasAdmin = hasRealmRole(event, 'admin') // Returns: boolean // 8. Check if user has resource/client role const hasManager = hasResourceRole(event, 'manager', 'my-app') // Returns: boolean // 9. Require authentication (throws 401 if not authenticated) try { const authUser = requireKeycloakAuth(event) // Returns: KeycloakTokenParsed // Throws: 401 Unauthorized if not authenticated } catch (error) { // Handle 401 error } // 10. Require specific realm role (throws 403 if missing) try { const adminUser = requireRealmRole(event, 'admin') // Returns: KeycloakTokenParsed // Throws: 401 if not authenticated, 403 if role missing } catch (error) { // Handle 401/403 errors } // 11. Require specific resource role (throws 403 if missing) try { const managerUser = requireResourceRole(event, 'manager', 'my-app') // Returns: KeycloakTokenParsed // Throws: 401 if not authenticated, 403 if role missing } catch (error) { // Handle 401/403 errors } return { utilities: { token: token ? 'present' : 'missing', user: user ? user.preferred_username : null, authenticated, roles: { hasAdmin, hasManager } } } }) ``` -------------------------------- ### Nuxt Keycloak Environment Variables Source: https://github.com/productdevbook/nuxt-keycloak/blob/main/README.md This example outlines environment variables for configuring the Nuxt Keycloak module. It distinguishes between public variables (exposed to the client) and private variables (server-only). This allows for environment-specific settings, such as different Keycloak instances or URLs for development and production. ```env # Public (exposed to client) NUXT_PUBLIC_KEYCLOAK_URL=https://keycloak.example.com NUXT_PUBLIC_KEYCLOAK_REALM=production NUXT_PUBLIC_KEYCLOAK_CLIENT_ID=nuxt-app NUXT_PUBLIC_APP_URL=https://app.example.com # Private (server-only) NUXT_KEYCLOAK_SERVER_VERIFY_TOKEN=true # true, false, or 'decode' NUXT_KEYCLOAK_SERVER_MIDDLEWARE=false ``` -------------------------------- ### Role-Based Access Control for Pages Source: https://github.com/productdevbook/nuxt-keycloak/blob/main/README.md This example shows how to implement role-based access control for Nuxt pages. It uses the `keycloak-auth` and `keycloak-role` middleware, along with `keycloakRoles` meta fields to specify required realm or resource roles for access. ```vue ``` -------------------------------- ### Configuring Web Origins (CORS) in Keycloak Source: https://github.com/productdevbook/nuxt-keycloak/blob/main/TROUBLESHOOTING.md This outlines the necessary Web Origins configuration within your Keycloak client settings to handle Cross-Origin Resource Sharing (CORS) requests from your Nuxt application. This is crucial for allowing your frontend to communicate with the Keycloak server. ```text http://localhost:3000 https://your-domain.com ``` -------------------------------- ### Configuring Redirect URIs in Keycloak Source: https://github.com/productdevbook/nuxt-keycloak/blob/main/TROUBLESHOOTING.md This section details how to add valid redirect and post-logout redirect URIs to your Keycloak client configuration. These URIs must match the ones used by your Nuxt application to ensure successful authentication flows. Wildcards can be used for flexibility, but specific paths are recommended for production environments. ```text http://localhost:3000/* http://localhost:3000 https://your-domain.com/* ``` -------------------------------- ### Disabling SSL Verification in Nuxt Config (Development) Source: https://github.com/productdevbook/nuxt-keycloak/blob/main/TROUBLESHOOTING.md This TypeScript code snippet demonstrates how to disable SSL certificate verification in the Nuxt configuration for development environments. This is useful when working with self-signed certificates but should NEVER be used in production due to security risks. ```typescript export default defineNuxtConfig({ keycloak: { server: { rejectUnauthorized: false // Disable in development only! } } }) ``` -------------------------------- ### Explicitly Importing Server Utilities Source: https://github.com/productdevbook/nuxt-keycloak/blob/main/README.md Shows how to explicitly import server utilities like `extractToken`, `verifyKeycloakToken`, and `requireRealmRole` from `nuxt-keycloak/server`. This provides more control over token handling and verification within server routes. ```typescript // server/api/custom.ts import { extractToken, verifyKeycloakToken, requireRealmRole } from 'nuxt-keycloak/server' export default defineEventHandler(async (event) => { const token = extractToken(event) const user = await verifyKeycloakToken(token) // Use imported functions requireRealmRole(event, 'admin') return { user } }) ``` -------------------------------- ### Configure Nuxt Keycloak Module Source: https://context7.com/productdevbook/nuxt-keycloak/llms.txt Configure the Nuxt Keycloak module by defining connection details and initialization options within the nuxt.config.ts file. This includes Keycloak server URL, realm, client ID, initialization options like onLoad and PKCE method, and server/client-side settings for token verification and refresh. ```typescript // nuxt.config.ts export default defineNuxtConfig({ modules: ['nuxt-keycloak'], keycloak: { // Required: Keycloak server configuration url: 'http://localhost:8080', realm: 'my-realm', clientId: 'nuxt-app', // Client initialization options initOptions: { onLoad: 'check-sso', // 'check-sso' or 'login-required' pkceMethod: 'S256', // Use PKCE for security flow: 'standard', // OAuth flow type checkLoginIframe: false, // Disable iframe checks silentCheckSsoRedirectUri: 'http://localhost:3000/silent-check-sso.html' }, // Server-side configuration server: { verifyToken: true, // true = JWKS verification, 'decode' = decode only, false = disabled middleware: false, // Enable global server middleware jwksCacheDuration: 600000, // Cache JWKS for 10 minutes rejectUnauthorized: true // Verify SSL certificates }, // Client-side token management client: { autoRefreshToken: true, // Automatically refresh tokens minTokenValidity: 30, // Refresh when < 30 seconds remain persistRefreshToken: true // Store refresh token in localStorage } } }) // Alternative: Use environment variables // .env // NUXT_PUBLIC_KEYCLOAK_URL=https://keycloak.example.com // NUXT_PUBLIC_KEYCLOAK_REALM=production // NUXT_PUBLIC_KEYCLOAK_CLIENT_ID=nuxt-app // NUXT_KEYCLOAK_SERVER_VERIFY_TOKEN=true // NUXT_KEYCLOAK_SERVER_MIDDLEWARE=false ``` -------------------------------- ### Configure Nuxt Keycloak Module Source: https://github.com/productdevbook/nuxt-keycloak/blob/main/README.md Demonstrates how to configure the nuxt-keycloak module in `nuxt.config.ts`. It includes setting the Keycloak server URL, realm, and client ID. Environment variables can also be used for configuration. ```typescript export default defineNuxtConfig({ modules: ['nuxt-keycloak'], keycloak: { url: 'http://localhost:8080', realm: 'your-realm', clientId: 'your-client-id', } }) ``` ```env NUXT_PUBLIC_KEYCLOAK_URL=http://localhost:8080 NUXT_PUBLIC_KEYCLOAK_REALM=your-realm NUXT_PUBLIC_KEYCLOAK_CLIENT_ID=your-client-id ``` -------------------------------- ### Server Utilities API Source: https://github.com/productdevbook/nuxt-keycloak/blob/main/README.md A collection of utility functions for server-side Keycloak integration, including token verification, extraction, and authentication checks. ```APIDOC ## Server Utilities ### Description Provides server-side utilities for interacting with Keycloak, such as verifying tokens, extracting credentials, and enforcing authentication and authorization. ### Available Functions - **`verifyKeycloakToken(token)`** - **Description**: Verifies a JWT token using Keycloak's JWKS. - **Parameters**: - `token` (string) - The JWT token to verify. - **Returns**: `Promise` - The decoded token payload if valid, otherwise null. - **`extractToken(event)`** - **Description**: Extracts the Bearer token from the `Authorization` header of an event. - **Parameters**: - `event` (object) - The Nuxt event object. - **Returns**: `string | null` - The extracted token or null if not found. - **`getKeycloakUser(event)`** - **Description**: Retrieves the authenticated Keycloak user information from the event context. - **Parameters**: - `event` (object) - The Nuxt event object. - **Returns**: `object | null` - The user object or null if not authenticated. - **`getKeycloakToken(event)`** - **Description**: Retrieves the access token from the event context. - **Parameters**: - `event` (object) - The Nuxt event object. - **Returns**: `string | null` - The access token or null if not available. - **`isAuthenticated(event)`** - **Description**: Checks if the user is authenticated. - **Parameters**: - `event` (object) - The Nuxt event object. - **Returns**: `boolean` - True if authenticated, false otherwise. - **`hasRealmRole(event, role)`** - **Description**: Checks if the authenticated user has a specific realm role. - **Parameters**: - `event` (object) - The Nuxt event object. - `role` (string) - The realm role to check for. - **Returns**: `boolean` - True if the user has the role, false otherwise. - **`hasResourceRole(event, role, resource?)`** - **Description**: Checks if the authenticated user has a specific client (resource) role. - **Parameters**: - `event` (object) - The Nuxt event object. - `role` (string) - The client role to check for. - `resource` (string, optional) - The resource (client ID) to check the role against. - **Returns**: `boolean` - True if the user has the role for the specified resource, false otherwise. - **`requireKeycloakAuth(event)`** - **Description**: Enforces authentication. Throws a 401 error if the user is not authenticated. - **Parameters**: - `event` (object) - The Nuxt event object. - **Throws**: `Error` with status code 401 if not authenticated. - **`requireRealmRole(event, role)`** - **Description**: Enforces realm role. Throws a 403 error if the user is missing the specified role. - **Parameters**: - `event` (object) - The Nuxt event object. - `role` (string) - The realm role required. - **Throws**: `Error` with status code 403 if the role is missing. - **`requireResourceRole(event, role, resource?)`** - **Description**: Enforces client role. Throws a 403 error if the user is missing the specified role for the resource. - **Parameters**: - `event` (object) - The Nuxt event object. - `role` (string) - The client role required. - `resource` (string, optional) - The resource (client ID) to check the role against. - **Throws**: `Error` with status code 403 if the role is missing for the resource. ``` -------------------------------- ### Nuxt Keycloak Module Configuration (TypeScript) Source: https://github.com/productdevbook/nuxt-keycloak/blob/main/README.md This code block shows the configuration options for the Nuxt Keycloak module in `nuxt.config.ts`. It covers essential settings like Keycloak server URL, realm, client ID, initialization options for the client-side, and server-side verification settings. This allows customization of the authentication flow and security parameters. ```typescript export default defineNuxtConfig({ keycloak: { // Keycloak server URL url: 'http://localhost:8080', // Realm name realm: 'my-realm', // Client ID (must be a public client) clientId: 'my-client', // Keycloak initialization options initOptions: { onLoad: 'check-sso', // or 'login-required' pkceMethod: 'S256', flow: 'standard', checkLoginIframe: false, silentCheckSsoRedirectUri: 'http://localhost:3000/silent-check-sso.html' }, // Server-side configuration server: { verifyToken: true, // true = full JWKS verification, false = disabled, 'decode' = decode only (for reverse proxy scenarios) middleware: false, // Enable global middleware jwksCacheDuration: 600000, // JWKS cache duration (10 minutes) rejectUnauthorized: true // Verify SSL certificates for JWKS endpoint }, // Client-side configuration client: { autoRefreshToken: true, // Auto-refresh tokens minTokenValidity: 30, // Refresh when < 30s validity persistRefreshToken: true // Store refresh token in localStorage } } }) ``` -------------------------------- ### Protecting Pages with Keycloak Middleware Source: https://github.com/productdevbook/nuxt-keycloak/blob/main/README.md Illustrates how to protect an entire Nuxt page using the `keycloak-auth` middleware. By defining `definePageMeta`, the specified middleware is applied to the page, ensuring only authenticated users can access it. ```vue ``` -------------------------------- ### Middleware Source: https://github.com/productdevbook/nuxt-keycloak/blob/main/README.md Information about the available middleware for protecting routes and enforcing role-based access control. ```APIDOC ## Middleware ### Description Provides middleware for Nuxt.js applications to protect routes and enforce role-based access control using Keycloak. ### Available Middleware - **`keycloak-auth`** - **Purpose**: Requires the user to be authenticated to access the route. - **Usage**: Apply this middleware to routes that need authentication. - **`keycloak-role`** - **Purpose**: Enforces role-based access control. This middleware is typically used in conjunction with route meta-data to specify required roles. - **Usage**: Configure route meta-data to specify roles, and then apply this middleware to protect those routes. ``` -------------------------------- ### Manual Token Verification Source: https://github.com/productdevbook/nuxt-keycloak/blob/main/README.md This endpoint demonstrates how to manually verify Keycloak tokens on the server side, including custom logic for role checks. ```APIDOC ## POST /api/custom ### Description Manually verifies a Keycloak token provided in the request and checks for specific realm roles. ### Method POST ### Endpoint /api/custom ### Parameters #### Request Body None (token is expected to be extracted from the request event) ### Request Example (No explicit request body, token is extracted from headers) ### Response #### Success Response (200) - **user** (object) - The verified user object. #### Response Example ```json { "user": { "sub": "a1b2c3d4-e5f6-7890-1234-567890abcdef", "email": "user@example.com", "name": "John Doe", "preferred_username": "johndoe", "given_name": "John", "family_name": "Doe", "realm_access": { "roles": [ "default-roles-my-realm", "special-access" ] } } } ``` #### Error Response (401) - **message** (string) - 'No token provided' or 'Invalid token' #### Error Response (403) - **message** (string) - 'Forbidden' (if the user lacks the 'special-access' realm role) ``` -------------------------------- ### Importing Nuxt Keycloak Server Utilities (TypeScript) Source: https://github.com/productdevbook/nuxt-keycloak/blob/main/README.md This TypeScript code snippet shows how to explicitly import server-side utility functions from the `nuxt-keycloak/server` module. These utilities, such as `verifyKeycloakToken` and `extractToken`, are essential for performing authentication and authorization checks within Nuxt server routes or API handlers. ```typescript import { verifyKeycloakToken, extractToken, requireKeycloakAuth } from 'nuxt-keycloak/server' ``` -------------------------------- ### Protecting API Routes with Server Utilities Source: https://github.com/productdevbook/nuxt-keycloak/blob/main/README.md Demonstrates how to protect Nuxt API routes using Keycloak server utilities. The `requireKeycloakAuth` and `requireRealmRole` functions can be used directly within `defineEventHandler` to enforce authentication and role checks on server requests. ```typescript // server/api/protected.ts export default defineEventHandler(async (event) => { // Require authentication - auto-imported const user = requireKeycloakAuth(event) return { message: 'Protected data', user } }) ``` ```typescript // server/api/admin.ts export default defineEventHandler(async (event) => { // Require specific role - auto-imported const user = requireRealmRole(event, 'admin') return { message: 'Admin data', user } }) ``` -------------------------------- ### Protect Server API Routes with Keycloak Helpers Source: https://context7.com/productdevbook/nuxt-keycloak/llms.txt Secure server API routes in Nuxt.js using auto-imported helper functions provided by the Keycloak integration. These functions handle authentication and role checking, throwing appropriate HTTP errors (401, 403) if conditions are not met. Inputs are the H3 event object and required roles/clients. ```typescript // server/api/protected.get.ts export default defineEventHandler(async (event) => { // Simple: Require authentication (throws 401 if not authenticated) const user = requireKeycloakAuth(event) return { message: 'Protected data', user: { id: user.sub, username: user.preferred_username, email: user.email } } }) ``` ```typescript // server/api/admin.get.ts export default defineEventHandler(async (event) => { // Require specific realm role (throws 401 if not authenticated, 403 if no role) const user = requireRealmRole(event, 'admin') return { message: 'Admin-only data', roles: user.realm_access?.roles || [], user: { id: user.sub, username: user.preferred_username, email: user.email } } }) ``` ```typescript // server/api/manager.get.ts export default defineEventHandler(async (event) => { // Require client/resource role (throws 403 if role missing) const user = requireResourceRole(event, 'manager', 'my-app') // Alternative: Use default client from config // const user = requireResourceRole(event, 'manager') return { message: 'Manager data', user: { id: user.sub, username: user.preferred_username } } }) ``` -------------------------------- ### Enable Global Server Middleware for Automatic Token Processing Source: https://context7.com/productdevbook/nuxt-keycloak/llms.txt This configuration enables global server middleware for the Nuxt Keycloak module, automatically processing and verifying tokens on all incoming server requests. The `verifyToken` option is set to `true` for full JWKS verification. This simplifies authentication logic within API routes. ```typescript // nuxt.config.ts export default defineNuxtConfig({ modules: ['nuxt-keycloak'], keycloak: { url: 'http://localhost:8080', realm: 'my-realm', clientId: 'nuxt-app', server: { verifyToken: true, // Full JWKS verification middleware: true, // Enable global middleware } } }) // server/api/auto-protected.get.ts // With middleware enabled, authentication happens automatically export default defineEventHandler(async (event) => { // User is already verified and in context by middleware const user = getKeycloakUser(event) const token = getKeycloakToken(event) const isAuth = isAuthenticated(event) if (!isAuth) { throw createError({ statusCode: 401, message: 'Authentication required' }) } // No need to manually extract or verify token return { message: 'Automatically authenticated by global middleware', user: { id: user?.sub, username: user?.preferred_username, email: user?.email } } }) // server/api/optional-auth.get.ts // With middleware enabled, auth is available but not required export default defineEventHandler(async (event) => { const isAuth = isAuthenticated(event) if (isAuth) { const user = getKeycloakUser(event) return { message: 'Authenticated user', username: user?.preferred_username } } return { message: 'Anonymous user', username: 'guest' } }) ``` -------------------------------- ### Configure for Reverse Proxy Token Verification Source: https://github.com/productdevbook/nuxt-keycloak/blob/main/README.md This configuration snippet shows how to set up the Nuxt Keycloak module to trust tokens pre-verified by a reverse proxy (like Traefik ForwardAuth). By setting `server.verifyToken` to `'decode'`, the module skips JWKS verification and only decodes the token. ```typescript export default defineNuxtConfig({ keycloak: { url: process.env.NUXT_PUBLIC_KEYCLOAK_URL, realm: process.env.NUXT_PUBLIC_KEYCLOAK_REALM, clientId: process.env.NUXT_PUBLIC_KEYCLOAK_CLIENT_ID, server: { verifyToken: 'decode', // Decode only, trust proxy verification middleware: true, }, } }) ``` ```env NUXT_KEYCLOAK_SERVER_VERIFY_TOKEN=decode ``` -------------------------------- ### Manual Token Verification with Custom Logic (TypeScript) Source: https://github.com/productdevbook/nuxt-keycloak/blob/main/README.md This snippet demonstrates how to manually verify a Keycloak token in a Nuxt server API route. It extracts the token, verifies it using `verifyKeycloakToken`, and checks for specific realm roles before allowing access. This provides granular control over authentication and authorization. ```typescript // server/api/custom.ts export default defineEventHandler(async (event) => { const token = extractToken(event) if (!token) { throw createError({ statusCode: 401, message: 'No token provided' }) } const user = await verifyKeycloakToken(token) if (!user) { throw createError({ statusCode: 401, message: 'Invalid token' }) } // Check custom logic if (!hasRealmRole(event, 'special-access')) { throw createError({ statusCode: 403, message: 'Forbidden' }) } return { user } }) ``` -------------------------------- ### Protect Nuxt Pages with Keycloak Middleware Source: https://context7.com/productdevbook/nuxt-keycloak/llms.txt Secure Nuxt.js pages by defining middleware in `definePageMeta`. This allows for authentication checks and role-based access control directly within page components. Dependencies include the 'keycloak-auth' and 'keycloak-role' middleware, and user/token data is accessible via `useKeycloak`. ```vue ``` ```vue ``` ```vue ``` -------------------------------- ### Client-Side Authentication with useKeycloak Composable Source: https://context7.com/productdevbook/nuxt-keycloak/llms.txt Utilize the auto-imported `useKeycloak` composable in Vue components to access authentication state and methods. This includes checking authentication status, user information, tokens, and performing actions like login, logout, and role checks. ```vue ``` -------------------------------- ### Manual Keycloak Token Verification and Custom Logic Source: https://context7.com/productdevbook/nuxt-keycloak/llms.txt Implement custom authentication and authorization logic on the server-side by manually extracting, verifying, and inspecting Keycloak tokens. This approach allows for complex conditional checks beyond standard role-based access. It utilizes functions like `extractToken`, `verifyKeycloakToken`, `hasRealmRole`, `hasResourceRole`, and `isTokenExpired`. ```typescript // server/api/custom-auth.get.ts export default defineEventHandler(async (event) => { // Extract token from Authorization header const token = extractToken(event) if (!token) { throw createError({ statusCode: 401, message: 'No authentication token provided' }) } // Verify token using JWKS (or decode if configured) const user = await verifyKeycloakToken(token) if (!user) { throw createError({ statusCode: 401, message: 'Invalid or expired token' }) } // Attach to context for other utilities event.context.keycloak = { authenticated: true, user, token } // Check custom conditions if (!hasRealmRole(event, 'verified-user')) { throw createError({ statusCode: 403, message: 'Account not verified' }) } // Check resource role with custom client if (!hasResourceRole(event, 'premium', 'subscription-service')) { throw createError({ statusCode: 403, message: 'Premium subscription required' }) } // Custom business logic const isActive = user.email_verified && !isTokenExpired(event) return { message: 'Custom authentication successful', user: { id: user.sub, username: user.preferred_username, email: user.email, emailVerified: user.email_verified, roles: user.realm_access?.roles || [] }, metadata: { isActive, tokenExpiry: user.exp, issuer: user.iss } } }) function isTokenExpired(event: H3Event): boolean { const user = getKeycloakUser(event) if (!user || !user.exp) return true const now = Math.floor(Date.now() / 1000) return user.exp < now } ``` -------------------------------- ### Configure Nuxt Keycloak for Traefik ForwardAuth Source: https://context7.com/productdevbook/nuxt-keycloak/llms.txt This configuration enables the Nuxt Keycloak module to work behind a reverse proxy like Traefik that handles JWT verification. The module is set to 'decode' tokens, trusting the proxy for actual verification. Global middleware is enabled to process decoded tokens. ```typescript // nuxt.config.ts - For Traefik ForwardAuth or similar export default defineNuxtConfig({ modules: ['nuxt-keycloak'], keycloak: { url: process.env.NUXT_PUBLIC_KEYCLOAK_URL, realm: process.env.NUXT_PUBLIC_KEYCLOAK_REALM, clientId: process.env.NUXT_PUBLIC_KEYCLOAK_CLIENT_ID, server: { verifyToken: 'decode', // Decode only, trust proxy verification middleware: true, // Enable global middleware to decode tokens } } }) // server/api/proxy-protected.get.ts // When verifyToken: 'decode' is set, tokens are decoded but not verified export default defineEventHandler(async (event) => { // With middleware enabled, user is already in context const user = getKeycloakUser(event) const isAuth = isAuthenticated(event) if (!isAuth) { throw createError({ statusCode: 401, message: 'Not authenticated by proxy' }) } return { message: 'Protected by Traefik ForwardAuth', user: { id: user?.sub, username: user?.preferred_username, // Token signature was verified by reverse proxy verifiedBy: 'traefik-forwardauth' } } }) ``` ```yaml // docker-compose.yml example with Traefik // services: // traefik: // image: traefik:v2.10 // command: // - "--providers.docker=true" // - "--entrypoints.web.address=:80" // labels: // - "traefik.http.middlewares.keycloak-auth.forwardauth.address=http://keycloak:8080/auth/realms/my-realm/protocol/openid-connect/userinfo" // - "traefik.http.middlewares.keycloak-auth.forwardauth.trustForwardHeader=true" ``` -------------------------------- ### Configure Nuxt Keycloak Token Decode Mode Source: https://context7.com/productdevbook/nuxt-keycloak/llms.txt This configuration sets the Nuxt Keycloak module to 'decode' mode for the `verifyToken` option. This mode decodes JWTs without performing cryptographic verification, making it suitable for scenarios where an upstream service (like a reverse proxy) has already validated the token. Global middleware is enabled. ```typescript // nuxt.config.ts export default defineNuxtConfig({ keycloak: { url: process.env.NUXT_PUBLIC_KEYCLOAK_URL, realm: process.env.NUXT_PUBLIC_KEYCLOAK_REALM, clientId: process.env.NUXT_PUBLIC_KEYCLOAK_CLIENT_ID, server: { // 'decode' = decode JWT without verification (for reverse proxy scenarios) // true = full JWKS verification (default, recommended) // false = skip all token processing verifyToken: 'decode', middleware: true } } }) // server/api/decoded-token.get.ts export default defineEventHandler(async (event) => { // Token is decoded but NOT cryptographically verified // Only use this when tokens are verified by trusted upstream service const token = extractToken(event) if (!token) { throw createError({ statusCode: 401, message: 'No token provided' }) } // This uses decodeKeycloakToken internally when verifyToken: 'decode' const user = await verifyKeycloakToken(token) if (!user) { throw createError({ statusCode: 401, message: 'Invalid token format' }) } // Token claims are available but signature was not verified return { message: 'Token decoded without verification', warning: 'Only use this mode behind trusted reverse proxy', user: { id: user.sub, username: user.preferred_username, email: user.email, roles: user.realm_access?.roles || [], exp: user.exp, iat: user.iat } } }) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.