# Identity System Migration Guide **Date**: 2025-01-27 **Purpose**: Guide for migrating projects to unified identity system **Status**: Complete --- ## Overview This guide provides instructions for migrating projects to use the unified identity system (Keycloak). --- ## Prerequisites - Keycloak deployed and configured - Realm created - Client configured - Users and roles set up --- ## Migration Steps ### Step 1: Install Keycloak Client ```bash pnpm add keycloak-js ``` ### Step 2: Configure Keycloak Client ```typescript import Keycloak from 'keycloak-js'; const keycloak = new Keycloak({ url: process.env.KEYCLOAK_URL || 'http://keycloak:8080', realm: process.env.KEYCLOAK_REALM || 'workspace', clientId: process.env.KEYCLOAK_CLIENT_ID || 'workspace-api', }); ``` ### Step 3: Initialize Keycloak ```typescript async function initKeycloak() { try { const authenticated = await keycloak.init({ onLoad: 'login-required', checkLoginIframe: false, }); if (authenticated) { console.log('User authenticated'); } } catch (error) { console.error('Keycloak initialization failed', error); } } ``` ### Step 4: Update Authentication **Before**: ```typescript // Old authentication const token = await getTokenFromLocalStorage(); const response = await fetch('/api/users', { headers: { 'Authorization': `Bearer ${token}`, }, }); ``` **After**: ```typescript // New Keycloak authentication const token = keycloak.token; const response = await fetch('/api/users', { headers: { 'Authorization': `Bearer ${token}`, }, }); ``` ### Step 5: Update Authorization **Before**: ```typescript // Old role checking if (user.roles.includes('admin')) { // Admin action } ``` **After**: ```typescript // New Keycloak role checking if (keycloak.hasRealmRole('admin')) { // Admin action } ``` ### Step 6: Update Backend ```typescript import { verifyToken } from '@workspace/shared-auth'; async function authenticateRequest(req: Request) { const token = req.headers.authorization?.replace('Bearer ', ''); if (!token) { throw new Error('No token provided'); } // Verify token with Keycloak const decoded = await verifyToken(token, { issuer: process.env.KEYCLOAK_ISSUER, audience: process.env.KEYCLOAK_CLIENT_ID, }); return decoded; } ``` --- ## Best Practices ### Token Management - Use Keycloak token refresh - Handle token expiration - Store tokens securely ### Role Management - Use realm roles for global permissions - Use client roles for application-specific permissions - Map roles consistently ### User Management - Use Keycloak user federation - Sync users from external systems - Manage users centrally --- ## Migration Checklist - [ ] Install Keycloak client - [ ] Configure Keycloak connection - [ ] Update authentication code - [ ] Update authorization code - [ ] Update backend verification - [ ] Test authentication - [ ] Test authorization - [ ] Update documentation - [ ] Migrate users - [ ] Set up user federation (if needed) --- **Last Updated**: 2025-01-27