corrad-af-2024/docs/06_AUTHENTIK_INTEGRATION_IMPLEMENTATION.md
Afiq bb98dc0262 Update Header and Documentation for Authentik Integration
- Changed logout link in Header.vue from "/logout" to "/api/auth/logout" to align with the new Authentik API structure.
- Enhanced implementation status documentation to reflect the completion of the backend authentication system, including OAuth2 integration, session management, and middleware setup.
- Updated the implementation plan to outline the completed authentication foundation and next steps for RBAC database and API development.
- Added a new document detailing the authentication implementation, including server API endpoints, middleware, and composable usage for a comprehensive overview of the authentication system.
2025-05-31 19:20:38 +08:00

27 KiB

Authentik Native Integration Implementation Guide

Overview

This document outlines the complete implementation of native integration between our RBAC application and Authentik, designed as a frontend interface directly connected to Authentik's data layer. Major Update: The system has been redesigned to eliminate manual synchronization in favor of native integration patterns.

Native Integration Architecture

Design Philosophy

  • No Manual Sync: System operates as native Authentik frontend
  • Direct API Integration: Real-time communication with Authentik backend
  • Simplified UX: User interface focuses on functionality, not sync management
  • Data Consistency: Single source of truth through direct integration

Integration Architecture

┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
│   RBAC App      │◄──►│   Direct API    │◄──►│   Authentik     │
│   (Frontend)    │    │   Integration   │    │   (Backend)     │
│                 │    │                 │    │                 │
│ • User Mgmt     │    │ • REST Client   │    │ • Users         │
│ • Groups/Roles  │    │ • Real-time     │    │ • Groups        │
│ • Applications  │    │ • Error Handle  │    │ • Applications  │
│ • Resources     │    │ • Validation    │    │ • Permissions   │
└─────────────────┘    └─────────────────┘    └─────────────────┘

Implemented Features

1. Native Form Integration

Standardized FormKit Implementation

// All forms now use consistent pattern
<FormKit 
  type="form" 
  @submit="handleSubmit"
  :actions="false"
>
  <!-- Form fields -->
</FormKit>

<!-- Custom action buttons -->
<div class="flex space-x-3">
  <rs-button @click="resetForm" variant="primary-outline">
    Reset Form
  </rs-button>
  <rs-button @click="submitToAuthentik" :disabled="!isFormValid">
    Create User
  </rs-button>
</div>

Direct API Submission Pattern

// composables/useAuthentikDirectAPI.js
export const useAuthentikDirectAPI = () => {
  const createUser = async (userData) => {
    // Direct API call to Authentik
    const response = await $fetch('/api/authentik/users', {
      method: 'POST',
      body: {
        username: userData.username,
        email: userData.email,
        name: `${userData.firstName} ${userData.lastName}`,
        attributes: {
          firstName: userData.firstName,
          lastName: userData.lastName,
          phone: userData.phone,
          department: userData.department,
          jobTitle: userData.jobTitle,
          employeeId: userData.employeeId
        },
        is_active: userData.isActive,
        groups: userData.groups
      }
    })
    return response
  }

  const createGroup = async (groupData) => {
    return await $fetch('/api/authentik/groups', {
      method: 'POST',
      body: {
        name: groupData.name,
        attributes: {
          description: groupData.description,
          department: groupData.department,
          parentGroup: groupData.parentGroup
        }
      }
    })
  }

  return { createUser, createGroup }
}

2. Resource Management Integration NEW

Resource API Client

// composables/useResourceAPI.js
export const useResourceAPI = () => {
  const createResource = async (type, data, applicationId) => {
    // Auto-generate key from name
    const key = data.name
      .toLowerCase()
      .replace(/[^a-z0-9]/g, '-')
      .replace(/-+/g, '-')
      .replace(/^-|-$/g, '')
    
    // Direct integration with Authentik permission system
    return await $fetch('/api/authentik/resources', {
      method: 'POST',
      body: {
        ...data,
        key,
        type,
        applicationId,
        authentikMetadata: {
          resourceType: type,
          generatedKey: key,
          applicationContext: applicationId
        }
      }
    })
  }

  const getResources = async (applicationId, type) => {
    return await $fetch(`/api/authentik/resources?app=${applicationId}&type=${type}`)
  }

  const deleteResource = async (resourceId) => {
    return await $fetch(`/api/authentik/resources/${resourceId}`, {
      method: 'DELETE'
    })
  }

  return { createResource, getResources, deleteResource }
}

Resource Data Structure

const resourceSchema = {
  // Menu Resources
  menus: [{
    id: String,
    name: String,           // Display name
    key: String,            // Auto-generated: "user-management"
    path: String,           // "/users"
    applicationId: String,  // "corradaf"
    authentikPermissionId: String, // Direct Authentik permission ID
    createdAt: Date
  }],
  
  // Component Resources  
  components: [{
    id: String,
    name: String,           // "User Profile Actions"
    key: String,            // Auto-generated: "user-profile-actions"
    description: String,    // "Edit, delete user profiles"
    applicationId: String,  // "corradaf"
    authentikPermissionId: String, // Direct Authentik permission ID
    actions: [String],      // ["view", "edit", "delete"]
    createdAt: Date
  }],
  
  // Feature Resources
  features: [{
    id: String,
    name: String,           // "Data Export"
    key: String,            // Auto-generated: "data-export"
    description: String,    // "Export data to CSV/Excel"
    applicationId: String,  // "corradaf"
    authentikPermissionId: String, // Direct Authentik permission ID
    createdAt: Date
  }]
}

3. Enhanced Role Templates System NEW

Template Management API

// composables/useRoleTemplates.js
export const useRoleTemplates = () => {
  const createTemplate = async (templateData) => {
    return await $fetch('/api/authentik/role-templates', {
      method: 'POST',
      body: {
        name: templateData.name,
        description: templateData.description,
        permissions: {
          menus: templateData.selectedMenus,
          components: templateData.selectedComponents,
          features: templateData.selectedFeatures
        },
        authentikRoleId: null, // Will be populated when template is used
        permissionCount: calculatePermissionCount(templateData)
      }
    })
  }

  const cloneTemplate = async (templateId, newName) => {
    const template = await getTemplate(templateId)
    return await createTemplate({
      ...template,
      name: newName,
      id: undefined // Remove ID for new template
    })
  }

  return { createTemplate, cloneTemplate }
}

Template-to-Role Conversion

const applyTemplateToRole = async (templateId, roleData) => {
  const template = await getTemplate(templateId)
  
  // Create role in Authentik with template permissions
  const authentikRole = await $fetch('/api/authentik/roles', {
    method: 'POST',
    body: {
      name: roleData.name,
      description: roleData.description,
      application: roleData.application,
      permissions: template.permissions,
      templateId: templateId,
      isGlobal: roleData.isGlobal,
      priority: roleData.priority
    }
  })
  
  return authentikRole
}

4. Application Quick Setup Integration Enhanced

Setup Type Handler

const applySetupType = async (setupType, applicationData) => {
  const setupConfigs = {
    'web-app': {
      providerType: 'oauth2',
      defaultScopes: ['openid', 'profile', 'email'],
      flowBindings: ['default-authentication-flow', 'default-authorization-flow'],
      policyEngine: 'any'
    },
    'api-service': {
      providerType: 'oauth2',
      defaultScopes: ['api:read', 'api:write'],
      flowBindings: ['api-authentication-flow'],
      policyEngine: 'all'
    },
    'enterprise-app': {
      providerType: 'saml',
      ssoConfiguration: 'enterprise-sso',
      flowBindings: ['enterprise-authentication-flow'],
      policyEngine: 'all'
    }
  }

  const config = setupConfigs[setupType]
  
  // Create application in Authentik with smart defaults
  return await $fetch('/api/authentik/applications', {
    method: 'POST',
    body: {
      ...applicationData,
      provider: {
        type: config.providerType,
        ...generateProviderConfig(config, applicationData)
      },
      policyEngineMode: config.policyEngine,
      flowBindings: config.flowBindings
    }
  })
}

🚀 Technical Implementation Patterns

Form Submission Pattern

// Standardized form submission across all pages
const handleFormSubmit = async (formData) => {
  isLoading.value = true
  
  try {
    // Direct API call - no sync logic needed
    const result = await authentikAPI.createEntity(formData)
    
    // Success handling
    await navigateTo('/success-page')
    
  } catch (error) {
    // Error handling
    console.error('Operation failed:', error)
    showErrorNotification(error.message)
  } finally {
    isLoading.value = false
  }
}

Real-time Data Pattern

// Real-time data fetching without sync concerns
const { data: users, refresh } = await useFetch('/api/authentik/users', {
  key: 'users-list',
  transform: (data) => data.map(transformAuthentikUser)
})

// Reactive data updates
watch(() => searchQuery.value, () => {
  refresh()
})

Progressive Disclosure Pattern

// Template-first approach with advanced options
const showAdvancedOptions = ref(false)
const useTemplate = ref(true)

const toggleAdvanced = () => {
  showAdvancedOptions.value = !showAdvancedOptions.value
  if (showAdvancedOptions.value) {
    useTemplate.value = false
  }
}

📱 User Interface Integration

Removed Sync Elements Major Update

  • No Sync Buttons: Removed all manual sync triggers
  • No Sync Status: Removed sync status indicators and badges
  • No Sync Sections: Removed "Integration" sections from forms
  • No Sync Stats: Removed "Synced to Authentik" statistics

Enhanced Navigation NEW

// Hierarchical navigation structure
const navigation = [
  {
    name: 'Roles',
    icon: 'ph:shield',
    children: [
      { name: 'Role List', path: '/roles' },
      { name: 'Templates', path: '/roles/templates' }
    ]
  },
  {
    name: 'Applications',
    icon: 'ph:app-window',
    children: [
      { name: 'Application List', path: '/applications' },
      { name: 'Resources', path: '/applications/resources' }
    ]
  }
]

Template-First Role Creation Enhanced

<!-- Role templates as primary method -->
<div class="role-templates">
  <div v-for="template in roleTemplates" :key="template.id">
    <div class="template-card" @click="selectTemplate(template.id)">
      <h4>{{ template.name }}</h4>
      <p>{{ template.description }}</p>
      <span>{{ template.permissionCount }} permissions</span>
    </div>
  </div>
</div>

<!-- Advanced permissions hidden by default -->
<rs-card v-if="showAdvancedPermissions">
  <template #header>
    <Icon name="ph:gear" class="text-orange-600" />
    <h3>Advanced Permissions</h3>
    <rs-badge variant="warning">Expert Mode</rs-badge>
  </template>
  <!-- Detailed permission configuration -->
</rs-card>

🔧 Configuration & Environment

Environment Configuration

// nuxt.config.ts
export default {
  runtimeConfig: {
    // Private keys (server-side only)
    authentikApiUrl: process.env.AUTHENTIK_API_URL,
    authentikApiToken: process.env.AUTHENTIK_API_TOKEN,
    
    // Public keys (client-side accessible)
    public: {
      authentikDomain: process.env.AUTHENTIK_DOMAIN,
      appName: process.env.APP_NAME || 'CorradAF RBAC'
    }
  }
}

API Proxy Configuration

// server/api/authentik/[...].js
export default defineEventHandler(async (event) => {
  const config = useRuntimeConfig()
  const path = getRouterParam(event, 'path')
  
  // Proxy requests to Authentik API
  return await $fetch(`${config.authentikApiUrl}/${path}`, {
    method: getMethod(event),
    headers: {
      'Authorization': `Bearer ${config.authentikApiToken}`,
      'Content-Type': 'application/json'
    },
    body: await readBody(event)
  })
})

📊 Implementation Status

Completed Integrations

Component Native Integration Form Standards UX Enhancement
User Management Complete :actions="false" Simplified
Group Management Complete :actions="false" Simplified
Role Management Complete :actions="false" Templates
Application Management Complete :actions="false" Quick Setup
Resource Management Complete :actions="false" Centralized

Removed Sync Elements

Page Sync Buttons Sync Status Integration Sections
/users Removed Removed Removed
/users/create Removed Removed Simplified
/groups Removed Removed Removed
/groups/create Removed Removed Simplified
/roles/create Removed Removed Simplified
/applications Removed Removed Removed
/applications/create Removed Removed Simplified
/rbac-permission Removed Removed Updated

Enhanced Features NEW

Feature Status Description
Role Templates Complete Pre-configured role templates with permission sets
Application Resources Complete Centralized resource management (menus, components, features)
Quick Setup Types Complete Template-based application configuration
Progressive Disclosure Complete Advanced options hidden by default
Hierarchical Navigation Complete Organized menu structure with sub-items

🎯 Integration Benefits

User Experience Benefits

  • Simplified Interface: No confusing sync options or status displays
  • Faster Workflows: Direct action without sync delays
  • Reduced Errors: No sync-related errors or failures
  • Consistent Behavior: Predictable responses to user actions

Technical Benefits

  • Real-time Updates: Immediate data consistency
  • Reduced Complexity: No sync state management needed
  • Better Performance: Direct API calls without sync overhead
  • Cleaner Code: Simplified business logic without sync concerns

Administrative Benefits

  • Template-First Approach: Common tasks simplified with smart defaults
  • Centralized Management: Single interface for all resource types
  • Progressive Disclosure: Expert features available when needed
  • Consistent Patterns: Same interaction patterns across all modules

🚧 Next Implementation Phase

Backend API Development (Priority 1)

  • Authentik API Proxy: Server-side API proxy for secure communication
  • Data Validation: Request/response validation middleware
  • Error Handling: Comprehensive error handling and logging
  • Authentication: Proper authentication flow implementation

Advanced Features (Priority 2)

  • Real-time Updates: WebSocket integration for live data updates
  • Bulk Operations: Efficient batch processing for large operations
  • Audit Logging: Comprehensive activity tracking
  • Advanced Search: Cross-entity search and filtering

Performance Optimization (Priority 3)

  • Caching Strategies: Intelligent caching for frequently accessed data
  • Lazy Loading: Optimized loading for large datasets
  • Request Optimization: Batch API calls and request optimization

Status: Native Authentik integration approach implemented with simplified UX, comprehensive resource management, and enhanced template systems. Manual sync functionality completely removed. Ready for backend API integration.

🎯 BACKEND AUTHENTICATION IMPLEMENTATION COMPLETED NEW

OAuth2/OIDC Authentication System 100% COMPLETE

// Server API Implementation - COMPLETED
/server/api/auth/
├── login.js           OAuth2 authorization redirect
├── callback.js        Token exchange and user session
├── logout.js          Session cleanup and redirect
├── me.js             Current user information
└── validate.js       Authentication validation

Authentication Flow Implementation COMPLETED

graph TD
    A[User visits protected route] --> B[Middleware checks auth]
    B --> C{Authenticated?}
    C -->|No| D[Redirect to /login]
    D --> E[User clicks Sign in with Authentik]
    E --> F[Redirect to Authentik OAuth2]
    F --> G[User authenticates with Authentik]
    G --> H[Authentik redirects to /api/auth/callback]
    H --> I[Exchange code for tokens]
    I --> J[Get user info from Authentik]
    J --> K[Set secure cookies]
    K --> L[Redirect to /dashboard]
    C -->|Yes| M[Allow access to route]

Server Utilities Implementation COMPLETED

// /server/utils/authentik.js - IMPLEMENTED
export const authenticateWithAuthentik = async (code, redirectUri) => {
  // Exchange authorization code for access token
  const tokenResponse = await fetch(`${config.authentikUrl}/application/o/token/`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams({
      grant_type: 'authorization_code',
      client_id: config.authentikClientId,
      client_secret: config.authentikClientSecret,
      code,
      redirect_uri: redirectUri
    })
  });
  // ... token handling and user info retrieval
}

// /server/utils/auth.js - IMPLEMENTED
export const requireAuth = async (event) => {
  const token = getCookie(event, 'auth_token');
  if (!token) {
    throw createError({ statusCode: 401, statusMessage: 'No token provided' });
  }
  // ... token validation with Authentik
}

Middleware System Implementation COMPLETED

// /middleware/auth.js - IMPLEMENTED
export default defineNuxtRouteMiddleware(async (to) => {
  const publicRoutes = ['/login', '/api/auth/login', '/api/auth/callback'];
  if (publicRoutes.includes(to.path)) return;
  
  try {
    await $fetch('/api/auth/validate');
  } catch (error) {
    return navigateTo('/login');
  }
});

// /middleware/dashboard.js - IMPLEMENTED
export default defineNuxtRouteMiddleware(async () => {
  try {
    await $fetch('/api/auth/validate');
    return navigateTo('/dashboard');
  } catch (error) {
    // User not authenticated, allow access to login page
  }
});

Authentication Composable Implementation COMPLETED

// /composables/useAuth.js - IMPLEMENTED
export const useAuth = () => {
  const user = ref(null);
  const isAuthenticated = computed(() => !!user.value);

  const checkAuth = async () => {
    try {
      const response = await $fetch('/api/auth/validate');
      return response.authenticated;
    } catch (error) {
      return false;
    }
  };

  const getCurrentUser = async () => {
    try {
      const userData = await $fetch('/api/auth/me');
      user.value = userData;
      return userData;
    } catch (error) {
      user.value = null;
      throw error;
    }
  };

  const login = () => {
    return navigateTo('/api/auth/login', { external: true });
  };

  const logout = async () => {
    await navigateTo('/api/auth/logout', { external: true });
  };

  return {
    user: readonly(user),
    isAuthenticated,
    checkAuth,
    getCurrentUser,
    login,
    logout,
    requireAuth
  };
};

Configuration Implementation COMPLETED

// nuxt.config.js - IMPLEMENTED
export default defineNuxtConfig({
  runtimeConfig: {
    // Private keys (server-side only)
    authentikUrl: process.env.AUTHENTIK_URL,
    authentikClientId: process.env.AUTHENTIK_CLIENT_ID,
    authentikClientSecret: process.env.AUTHENTIK_CLIENT_SECRET,
    authentikApiToken: process.env.AUTHENTIK_API_TOKEN,
    appUrl: process.env.APP_URL,
    
    // Public keys (client-side accessible)
    public: {
      authentikUrl: process.env.AUTHENTIK_URL
    }
  }
})

Frontend Pages Implementation COMPLETED

// /pages/login.vue - IMPLEMENTED
<template>
  <div class="min-h-screen flex items-center justify-center bg-gray-50">
    <button @click="loginWithAuthentik" class="...">
      Sign in with Authentik
    </button>
  </div>
</template>

// /pages/dashboard.vue - IMPLEMENTED  
<script setup>
definePageMeta({ middleware: 'auth' });
const { logout } = useAuth();
const { data: user } = await useFetch('/api/auth/me', { server: false });
</script>

// /pages/index.vue - IMPLEMENTED
<script setup>
definePageMeta({ middleware: 'main' });
</script>

📊 UPDATED IMPLEMENTATION STATUS

Authentication Integration 100% COMPLETE (Was: Priority 1)

  • OAuth2/OIDC Setup: Complete Authentik OAuth2 flow implemented
  • Session Management: Secure cookie-based session handling
  • Route Protection: Middleware-based authentication for all protected routes
  • User Context: Complete user information available throughout app
  • Token Validation: Real-time token verification with Authentik API

Backend API Foundation 100% COMPLETE (Was: Priority 1)

  • Authentication Endpoints: All auth endpoints implemented and tested
  • Middleware System: Complete route protection and validation
  • Utility Functions: Server-side auth checking and validation
  • Error Handling: Comprehensive error management and user feedback
  • Security: Secure token handling, validation, and cookie management

Frontend Integration 100% COMPLETE (Was: Priority 2)

  • Authentication UI: Clean, user-friendly login/logout interface
  • Protected Routing: Automatic route protection based on auth status
  • State Management: Reactive authentication state management
  • User Experience: Smooth authentication flow with proper redirects
  • Composable Integration: Reusable authentication logic across components

RBAC Database Schema NEXT PRIORITY (Was: Priority 3)

  • Prisma Schema: Database schema for RBAC entities
  • Migration Scripts: Database setup and migration management
  • Seed Data: Default applications, roles, and permissions
  • Data Relationships: Application → Groups → Roles → Users hierarchy

RBAC API Development HIGH PRIORITY (NEW)

  • Application CRUD: Complete application management API
  • User Management: User creation, assignment, and management
  • Group Management: Group creation and role collection management
  • Role Management: Role creation and permission assignment
  • Permission Checking: Real-time permission validation endpoints

📊 UPDATED IMPLEMENTATION METRICS

Completed Integrations UPDATED

Component Authentication API Foundation Frontend Integration RBAC Integration
Authentication System 100% 100% 100% Ready
User Management 100% Ready Ready Pending
Group Management 100% Ready Ready Pending
Role Management 100% Ready Ready Pending
Application Management 100% Partial Ready Pending

Authentication Foundation Metrics NEW

Feature Implementation Testing Integration
OAuth2 Flow Complete Tested Integrated
Session Management Complete Tested Integrated
Route Protection Complete Tested Integrated
User Context Complete Tested Integrated
Error Handling Complete Tested Integrated

Environment Setup REQUIRED

# Required Environment Variables - DOCUMENTED
AUTHENTIK_URL=http://localhost:9000
AUTHENTIK_CLIENT_ID=your_client_id
AUTHENTIK_CLIENT_SECRET=your_client_secret
AUTHENTIK_API_TOKEN=your_api_token
APP_URL=http://localhost:3000

🎯 UPDATED INTEGRATION BENEFITS

Authentication Benefits Achieved

  • Production-Ready Security: OAuth2/OIDC compliance with Authentik
  • Seamless User Experience: Single sign-on with smooth redirects
  • Session Management: Secure, persistent authentication state
  • Route Protection: Automatic protection of sensitive areas
  • Error Handling: Graceful handling of auth failures and timeouts

Technical Foundation Benefits

  • Scalable Architecture: Modular, extensible authentication system
  • Clean Separation: Clear separation between auth and business logic
  • Developer Experience: Easy-to-use composables and utilities
  • Security Best Practices: Secure token handling and validation
  • Future-Ready: Foundation ready for RBAC implementation

RBAC Foundation Ready

  • User Context Available: User information accessible throughout app
  • API Structure Ready: Server endpoints prepared for RBAC APIs
  • Frontend Ready: UI components ready for RBAC features
  • Middleware Framework: Route protection ready for permission checking
  • Configuration System: Environment setup ready for RBAC settings

🚧 UPDATED NEXT IMPLEMENTATION PHASE

Database Schema Development IMMEDIATE PRIORITY

  • Prisma Schema: Implement complete RBAC database schema
  • Migration Management: Database setup and versioning
  • Seed Data Creation: Default applications, roles, and permissions
  • Relationship Validation: Proper foreign key constraints and relationships

RBAC API Development HIGH PRIORITY

  • Application Management API: CRUD operations for applications
  • User Assignment API: User creation and application assignment
  • Group Management API: Group creation and role assignment
  • Role Management API: Role creation and permission management
  • Permission Validation API: Real-time permission checking

Frontend RBAC Integration MEDIUM PRIORITY

  • Application Management UI: Connect frontend to application API
  • User Management Integration: Full user creation and management
  • Permission-Based Navigation: Dynamic menu based on user permissions
  • Role-Based Components: Component visibility based on user roles