Role-Based Access Control (RBAC) with Keycloak
Learn how to implement secure, scalable RBAC with Keycloak across backend (FastAPI) and frontend (React) applications.
Introduction
In modern applications, especially in multi-tenant or enterprise environments, securing access to resources is paramount. Role-Based Access Control (RBAC) offers a systematic approach to manage who can access what, based on defined roles. With Keycloak, an open-source Identity and Access Management tool, RBAC becomes robust and highly configurable. This guide walks through how to implement and enforce RBAC using Keycloak in both backend (FastAPI) and frontend (React) applications.
Table of Contents
- What is Role-Based Access Control (RBAC)?
- Creating and Managing Roles in Keycloak
- Protecting Backend Routes with FastAPI
- Frontend Access Control in React
- Best Practices for Role Management
- Conclusion
- References
- What’s Next?
What is Role-Based Access Control (RBAC)?
RBAC is a security paradigm that restricts access to resources based on a user’s assigned roles. Rather than assigning permissions to each user individually, roles are created for various job functions, and users are assigned to those roles. Each role then has specific permissions associated with it.
This approach simplifies permission management, especially in large systems. For example, an “Admin” might have full access to all operations, while a “Viewer” might only read data. RBAC ensures that users only see and do what they’re allowed to, reducing the risk of accidental or malicious data exposure.
Creating and Managing Roles in Keycloak
Keycloak allows administrators to define and manage roles at both the Realm and Client levels. Realm roles are global across the Keycloak instance, while Client roles are specific to an application (client).
Steps:
- Login to the Keycloak admin console.
- Navigate to your Realm → Roles → Create Role.
- Assign roles directly to users or through groups.
- For Client roles: Go to Clients → [Your Client] → Roles → Create.
Keycloak also supports composite roles, enabling role hierarchies. For example, an admin
role can include editor
and viewer
roles. This flexibility allows for granular permission structures tailored to your app’s needs. In this post we will work with realms roles.

Protecting Backend Routes with FastAPI
In FastAPI, we can protect routes by validating the JWT access token issued by Keycloak. Middleware or dependency functions can extract and verify roles from the token. Just to know which role it is, you should modify the decode_token function in the AuthMiddleware class
def decode_token(self, token: str):
token_ = token.replace('Bearer ', '')
payload = KEYCLOAK_OPENID.decode_token(token_)
global the_user
the_user = payload
print("The roles are")
print(payload.get('realm_access',{}).get('roles',{}))
return payload
This ensures that only users with the correct role can access protected endpoints.
Frontend Access Control in React
On the frontend, you can decode the access token and use roles to conditionally render components. Here we add the new code snippet that you must add to App.jsx to the post project
const getRoles = () => {
try {
if (keycloakInstance.token) {
const decoded = jwtDecode(keycloakInstance.token);
const userRoles = decoded?.realm_access?.roles || [];
setRoles(userRoles);
console.log("User roles:", userRoles);
}
} catch (error) {
console.error("Failed to decode token:", error);
}
};
This approach enhances the user experience by only showing relevant UI elements while enforcing access control in the backend.
Best Practices for Role Management
- Avoid hardcoding roles: Centralize role names and access logic.
- Use custom claims: Add business-specific attributes in tokens if needed.
- Implement scopes: Use OAuth2 scopes to define fine-grained access.
- Audit regularly: Periodically review assigned roles and permissions.
- Secure tokens: Ensure tokens are short-lived and transmitted over HTTPS.
Adopting these practices helps maintain a secure, manageable, and scalable RBAC system.
Conclusion
RBAC with Keycloak provides a powerful way to manage permissions across your systems. By defining roles centrally and enforcing them in both frontend and backend, you ensure a clean separation of concerns and reduce security risks. FastAPI and React make it easy to integrate with Keycloak and apply role-based logic where it matters most.
References
What’s Next?
- Integrating Keycloak with GitLab CI/CD for dev/test environments.
- Managing custom user attributes and dynamic permissions.
- Implementing Attribute-Based Access Control (ABAC) with Keycloak.
- Token introspection and refresh strategies in SPAs.
- SSO across multiple microservices using Keycloak Gatekeeper.