### 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
Welcome, {{ user?.username }}!
```
--------------------------------
### 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