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
.envfile 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
- Create a Client in Keycloak:
- Log in to the Keycloak Admin Console (http://localhost:8081/admin)
- Select the realm (default: "master")
- Go to "Clients" and click "Create"
- Set "Client ID" to "fastapi-client" (or your preferred name)
-
Click "Save"
-
Configure the Client:
- Set "Access Type" to "confidential"
- Enable "Service Accounts Enabled"
- Set "Valid Redirect URIs" to include "http://localhost:8000/*"
-
Click "Save"
-
Get the Client Secret:
- Go to the "Credentials" tab
- Copy the "Secret" value
- Update your
.envfile with this secret
Authentication Flow
The Meta Agent Platform implements the following authentication flows:
Authorization Code Flow (for browser-based applications)
- User navigates to
/login - User is redirected to Keycloak login page
- After successful login, Keycloak redirects to
/callbackwith an authorization code - The backend exchanges the code for tokens
- User is authenticated and redirected to the home page
Client Credentials Flow (for service-to-service communication)
- Service makes a request to
/token - The backend uses client credentials to obtain a token from Keycloak
- Service uses the token for subsequent API calls
API Authentication
All protected API endpoints require a valid JWT token in the Authorization header:
Using Swagger UI
- Navigate to http://localhost:8000/docs
- Click the "Authorize" button
- Enter your credentials or use the client credentials flow
- 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
- Log in to the Keycloak Admin Console
- Select your realm
- Go to "Roles" and click "Add Role"
- Create roles like "user" and "admin"
- Go to "Users" and select a user
- Go to the "Role Mappings" tab
- Assign the appropriate roles
User Synchronization
The Meta Agent Platform automatically synchronizes users between Keycloak and the database:
- When a user authenticates through Keycloak, their information is retrieved from the token
- The backend checks if the user exists in the database by their Keycloak ID
- If the user exists, their information is updated
- 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:
- Log in to the Keycloak Admin Console
- Select your realm
- Go to "Client Scopes" and select or create a scope
- Add mappers to include the desired claims
Modifying Token Validation
The token validation logic is in app/core/auth.py. To modify it:
- Update the
decode_tokenmethod to include additional validation - Update the
get_current_usermethod to extract additional claims
Troubleshooting
Token Validation Issues
If you encounter token validation issues:
- Check that your Keycloak server is running
- Verify the client configuration in Keycloak
- Check that the client secret in your
.envfile matches the one in Keycloak - Inspect the token using a tool like jwt.io
Authentication Flow Issues
If the authentication flow is not working:
- Check the redirect URIs in your Keycloak client configuration
- Verify that the client is set to "confidential" and has service accounts enabled
- Check the browser console for any errors during the redirect
Role-Based Access Issues
If role-based access is not working:
- Verify that the user has the required roles in Keycloak
- Check that the roles are included in the token (inspect the token)
- Verify that the role names match exactly between Keycloak and the code