Skip to content

Keycloak Authentication Guide

This guide explains how to work with Keycloak authentication in the Meta Agent Platform.

Prerequisites

  • Keycloak server running (default: http://localhost:8081)
  • Project dependencies installed
  • .env file configured with Keycloak connection details

Keycloak Configuration

Ensure your .env file contains the following Keycloak configuration:

# Keycloak settings
KEYCLOAK_SERVER_URL=http://localhost:8081/
KEYCLOAK_REALM=master
KEYCLOAK_CLIENT_ID=fastapi-client
KEYCLOAK_CLIENT_SECRET=your-client-secret

Keycloak Client Setup

  1. Create a Client in Keycloak:
  2. Log in to the Keycloak Admin Console (http://localhost:8081/admin)
  3. Select the realm (default: "master")
  4. Go to "Clients" and click "Create"
  5. Set "Client ID" to "fastapi-client" (or your preferred name)
  6. Click "Save"

  7. Configure the Client:

  8. Set "Access Type" to "confidential"
  9. Enable "Service Accounts Enabled"
  10. Set "Valid Redirect URIs" to include "http://localhost:8000/*"
  11. Click "Save"

  12. Get the Client Secret:

  13. Go to the "Credentials" tab
  14. Copy the "Secret" value
  15. Update your .env file with this secret

Authentication Flow

The Meta Agent Platform implements the following authentication flows:

Authorization Code Flow (for browser-based applications)

  1. User navigates to /login
  2. User is redirected to Keycloak login page
  3. After successful login, Keycloak redirects to /callback with an authorization code
  4. The backend exchanges the code for tokens
  5. User is authenticated and redirected to the home page

Client Credentials Flow (for service-to-service communication)

  1. Service makes a request to /token
  2. The backend uses client credentials to obtain a token from Keycloak
  3. Service uses the token for subsequent API calls

API Authentication

All protected API endpoints require a valid JWT token in the Authorization header:

Authorization: Bearer <token>

Using Swagger UI

  1. Navigate to http://localhost:8000/docs
  2. Click the "Authorize" button
  3. Enter your credentials or use the client credentials flow
  4. All API requests will include the token

Using curl

# Get a token using client credentials
curl -X POST "http://localhost:8081/realms/master/protocol/openid-connect/token" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=client_credentials" \
  -d "client_id=fastapi-client" \
  -d "client_secret=your-client-secret"

# Use the token to access a protected endpoint
curl -X GET "http://localhost:8000/protected" \
  -H "Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICIwNG5nNkpLbF9KQmVKYnBmai1yWkxuMG4yUFFIZ25rYldkWjU0aFRCZGxBIn0..."

Role-Based Access Control

The Meta Agent Platform implements role-based access control using Keycloak roles:

  • /protected - Requires the "user" role
  • /api/v1/users/{user_id} - Requires the "admin" role
  • /api/v1/users - Requires the "admin" role

Assigning Roles in Keycloak

  1. Log in to the Keycloak Admin Console
  2. Select your realm
  3. Go to "Roles" and click "Add Role"
  4. Create roles like "user" and "admin"
  5. Go to "Users" and select a user
  6. Go to the "Role Mappings" tab
  7. Assign the appropriate roles

User Synchronization

The Meta Agent Platform automatically synchronizes users between Keycloak and the database:

  1. When a user authenticates through Keycloak, their information is retrieved from the token
  2. The backend checks if the user exists in the database by their Keycloak ID
  3. If the user exists, their information is updated
  4. If the user doesn't exist, a new user record is created

Customizing Authentication

Adding Custom Claims to Tokens

To add custom claims to tokens, you can configure Keycloak to include them:

  1. Log in to the Keycloak Admin Console
  2. Select your realm
  3. Go to "Client Scopes" and select or create a scope
  4. Add mappers to include the desired claims

Modifying Token Validation

The token validation logic is in app/core/auth.py. To modify it:

  1. Update the decode_token method to include additional validation
  2. Update the get_current_user method to extract additional claims

Troubleshooting

Token Validation Issues

If you encounter token validation issues:

  1. Check that your Keycloak server is running
  2. Verify the client configuration in Keycloak
  3. Check that the client secret in your .env file matches the one in Keycloak
  4. Inspect the token using a tool like jwt.io

Authentication Flow Issues

If the authentication flow is not working:

  1. Check the redirect URIs in your Keycloak client configuration
  2. Verify that the client is set to "confidential" and has service accounts enabled
  3. Check the browser console for any errors during the redirect

Role-Based Access Issues

If role-based access is not working:

  1. Verify that the user has the required roles in Keycloak
  2. Check that the roles are included in the token (inspect the token)
  3. Verify that the role names match exactly between Keycloak and the code