← Back to Blog

Creating Applications with Different Access Levels Using Keycloak (RBAC)

July 19, 2024
8 min read
Keycloak
RBAC
Authentication
Python
FastAPI

Why are different access levels important?

Different access levels in applications are important for many reasons. Imagine you have a castle with different rooms, and not every guest needs the keys to all the doors. Similarly, in applications, different users need different access rights to perform their tasks without interfering with others.

Firstly, it is a matter of security. If every user had full access to all data and functions, it would increase the risk of information leaks and cyberattacks. For example, regular users do not need to see confidential information such as company financial data or personal data of other users. By restricting access, you can minimize such risks and protect important resources.

Additionally, it helps manage resources and maintain order in the system. For example, administrators have access to everything because they are responsible for configuring and managing the entire system. They can create and delete accounts, change configurations, and monitor the application's performance. Users, on the other hand, may only have access to the functions they need to perform their tasks. This prevents accidental errors and abuses.

Access level separation also reflects the organizational structure. Every company has its levels of hierarchy: administrators, managers, employees, and possibly even guests. Each has its roles and responsibilities. Managers, for example, can manage their teams and view reports but cannot change system settings. Guests may simply view public information without making changes or seeing protected data.

Common Access Level Examples

  1. Administrators — like the main key holders. They have access to all rooms (data and functions) because they need to oversee the entire castle (system). They create accounts, assign roles, and ensure everything runs smoothly.
  2. Regular users — have access only to the rooms where they work. For example, in a project management system, users can create and edit tasks but cannot change the project's overall settings or manage other users.
  3. Guests — like visitors who came to see the castle. They can only view public areas, such as product information on the website, but cannot place orders or see prices intended only for registered users.

Thus, different access levels help maintain order, security, and system efficiency. It allows each user to perform their tasks without interfering with others and without exposing the system to unnecessary risks.

What is Keycloak?

Keycloak is a powerful open-source identity and access management solution. Think of it as a security guard for your application, ensuring that only the right people have access to the appropriate resources. It offers Single Sign-On (SSO), identity federation, and user management, simplifying administration and enhancing security.

Key features of Keycloak in the context of access management

Single Sign-On (SSO)

Like a master key for all doors. Users can log in once and access all related applications without re-entering their password. Convenient and secure.

User Management

Keycloak allows creating and managing user accounts. You can set up various authentication methods, including passwords, two-factor authentication (2FA), and login through social networks.

Roles and Permissions

You can create roles and assign them to users, controlling who can do what in your application. For example, administrators will have full access, while regular users will only access their tasks.

Security Protocols

Keycloak supports modern security protocols such as OAuth 2.0, OpenID Connect, and SAML, ensuring robust authentication and authorization that meets standards.

Additional Features

Keycloak also supports integration with external identity providers like LDAP and Active Directory, allowing easy user and group management. It provides audit and monitoring capabilities, helping with security monitoring and threat detection.

Integration with FastAPI and Python

Keycloak easily integrates with FastAPI and Python applications. Using the python-keycloak library, you can connect to Keycloak, obtain access tokens, and check user roles, making your code more secure and manageable.

1from fastapi import FastAPI, Depends
2from fastapi_keycloak import FastAPIKeycloak, OIDCUser
3
4
5app = FastAPI()
6keycloak = FastAPIKeycloak(
7 server_url="http://localhost:8080/auth",
8 client_id="your-client-id",
9 client_secret="your-client-secret",
10 realm="your-realm",
11 callback_uri="http://localhost:8000/callback"
12)
13
14@app.get("/protected")
15def protected_route(user: OIDCUser = Depends(keycloak.get_current_user)):
16 return {"message": f"Hello, {user.username}"}
17
18if __name__ == "__main__":
19 import uvicorn
20 uvicorn.run(app, host="0.0.0.0", port=8000)

With this approach, you can easily manage access to different parts of your application, ensuring security and convenience for users. Keycloak provides powerful tools for access management, significantly simplifying the setup of authentication and authorization in modern web applications.

Basic Keycloak Setup

Before we can implement role-based access control, we need to set up Keycloak and configure it for our application. This involves creating a realm, setting up clients, and defining roles.

Creating a new realm

Open your browser and go to the address of your Keycloak server, usually http://localhost:8080/auth for a local installation. Enter your credentials, and you will be in the admin console.

Now let's create a new realm. In the upper left corner, you will see a dropdown menu, click on it, and select "Add realm". A window will appear where you need to enter the name of the new realm. Let's call it "test realm". Click "Create" and done — your new realm is created.

Client (Application) Configuration

After creating the realm, we need to configure the client, which is the application that will use Keycloak for authentication. In the left menu, select "Clients" and click "Create client". On the new page, you need to enter the client ID, for example, "my-app". Leave the client type as "OpenID Connect".

Next, select Client authentication. For public applications, it should be turned off.

Next, specify the redirect URLs (Valid Redirect URIs). These are the URLs to which the user will be redirected after authentication. For example, specify http://localhost:8000. Click "Save".

Now your client is created and configured. You can check and configure additional client parameters, such as session settings, access rights, and more, in the "Clients" section of the admin console.

Setup Complete

That's it! We have created and configured a new realm "test realm" and a client "my-app". Now you are ready to integrate Keycloak with your FastAPI application and enjoy all the benefits of centralized access management.

Creating and Managing Roles in Keycloak

Now that we have our realm and client set up, let's create and manage roles to implement role-based access control (RBAC) in our application.

Role Definition

Now that we have our realm and client, let's deal with roles. Roles in Keycloak are like distributing keys for different doors in your castle. They define who can do what in your application.

Creating roles in Keycloak is quite simple. In the admin console, go to your realm "test realm", and then select "Roles" in the left menu. There you will see the "Add Role" button. Click on it to create a new role. Give it a name, for example, "admin" for administrators, "user" for regular users, or "guest" for guests. Click "Save", and the new role will be created.

Common Role Examples

  • Administrator — a person who has full access to all functions and settings of the system. They can create and delete accounts, manage configurations, and oversee the entire system.
  • User — a person who uses your application to perform their tasks. They may have access to various functions of the application but cannot make changes to the system settings or manage other users.
  • Guest — a person who has minimal access. Usually, they can only view information without being able to make changes or access protected data.

By creating and assigning roles, you can clearly define who can do what in your application, ensuring security and manageability.

Assigning Roles to Users

Now that we have created roles, let's see how to assign them to users. This will help us clearly distribute rights and access in our application.

Creating Users in Keycloak

First, you need to create users. In the Keycloak admin console, go to your realm "test realm", then select "Users" in the left menu. There you will see the "Add user" button. Click on it to create a new user. Fill in the necessary fields, such as username, email, etc., and click "Save".

Assigning Roles to Users

After creating the user, you will be redirected to their profile page. Here you can configure many parameters, but we are interested in the "Role Mappings" tab. Go to this tab.

In the "Available Roles" section, select the role you want to assign to the user, for example, "admin", "user", or "guest", and click "Add selected". The selected role will now be displayed in the "Assigned Roles" section, meaning the user has received all the rights and accesses associated with this role.

And that's how easily you can create users and assign them roles in Keycloak. This will help you manage access to your application and ensure that each user has access only to the functions and data they need.

Integrating Keycloak with a Python Application

Now that we have set up Keycloak and configured roles, let's integrate it with our Python application to implement role-based access control.

Installing Necessary Libraries

Now let's integrate Keycloak with our Python application. For this, we will need a few libraries. The most popular library for working with Keycloak in Python is called python-keycloak. Let's start by installing it.

1pip install python-keycloak

Done! The library is installed, and now we can use it in our project.

Examples of Using the Library

Let's see how we can use `python-keycloak` to work with Keycloak. First, we need to create a Keycloak client instance:

1from keycloak import KeycloakOpenID
2
3keycloak_openid = KeycloakOpenID(server_url="http://localhost:8080/auth/",
4 client_id="your-client-id",
5 realm_name="your-realm",
6 client_secret_key="your-client-secret")

Now we can use this client for various operations, such as obtaining an access token:

1token = keycloak_openid.token("username", "password")

After obtaining the token, we can use it to access protected resources. Here is an example of a request using the token:

1import requests
2
3headers = {
4 "Authorization": f"Bearer {token['access_token']}"
5}
6
7response = requests.get("http://localhost:8000/protected", headers=headers)
8
9print(response.json())

This simple example shows how easy it is to integrate Keycloak with your Python application. We installed the necessary library, created a client to interact with Keycloak, and used the token to access protected resources. Now your application is ready to use centralized access management with Keycloak.

Role-Based Access Control

With Keycloak integrated into your application, you can now implement role-based access control by checking the user's roles in the token. This allows you to restrict access to certain parts of your application based on the user's role.

1# Decode the token to get user info and roles
2token_info = keycloak_openid.introspect(token['access_token'])
3
4# Check if the user has the 'admin' role
5if 'admin' in token_info.get('realm_access', {}).get('roles', []):
6    # Allow access to admin features
7    print("User has admin access")
8else:
9    # Restrict access
10    print("User does not have admin access")

Conclusion

In this article, we've explored how to use Keycloak to implement role-based access control (RBAC) in your applications. We've covered the importance of different access levels, what Keycloak is and its key features, how to set up Keycloak, create and manage roles, and integrate it with a Python application.

By using Keycloak for authentication and authorization, you can ensure that your application is secure and that users only have access to the resources they need. This not only improves security but also makes your application more manageable and user-friendly.

Remember that proper access control is a critical aspect of application security. By implementing RBAC with Keycloak, you're taking a significant step towards protecting your application and its data.

Need help with Keycloak RBAC implementation?
I offer expert consultation on Keycloak setup, role-based access control, and integration with various applications. Let's discuss how I can help you implement secure authentication for your projects.