This project provides an example of a Custom Protocol Mapper for Keycloak. It adds a list of companies associated with a user, retrieved from database, to the claims of the token.
The goal is to provide a starting point for developers looking to implement their own custom protocol mapper tailored to specific requirements.
- Add a list of companies (fetched from database) to the token claims
- Allows dynamic configuration of database connection parameters via the Keycloak interface
- Java : Version 11 or higher
- Keycloak : Version 15 or higher
- A relational database (e.g. MariaDB)
- Maven environment for building the project
For this example, we use a database with two tables : users and companies
CREATE TABLE users (
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(50) NOT NULL UNIQUE
);
CREATE TABLE companies (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
label VARCHAR(50) NOT NULL,
user_id INT NOT NULL,
FOREIGN KEY (user_id) REFERENCES users(id)
);INSERT INTO users (username) VALUES ('john_doe'), ('jane_doe');
INSERT INTO companies (name, label, user_id) VALUES
('Company A', 'Label A', 1),
('Company B', 'Label B', 1),
('Company C', 'Label C', 2);- Clone the repository :
git clone https://github.com/Pitchouneee/custom-protocol-mapper.git cd custom-protocol-mapper - Build and package the project :
mvn clean install
- Coy the generated JAR (
target/custom-protocol-mapper-<version>.jar)to theprovidersdirectory of your Keycloak installation - Restart Keycloak server :
./bin/kc.sh start
- Log in to the Keycloak admin console
- Got to the Clients tab, select the desired client
- Navigate to the Client scopes tab and select the dedicated client
- Now, in the Mappers tab, add a mapper by configuration :
- Mapper Type :
Custom Token Mapper. - Set the name of the claim (e.g.
companies) - Set the JDBC parameters :
JDBC Driver:org.mariadb.jdbc.DriverJDBC URL: e.g.,jdbc:mariadb://localhost:3306/mydbDatabase Username:rootDatabase Password:password
- Mapper Type :
- Save the configuration
Once configured, the token will include a custom claim containing the list of companies associated with the authenticated user
Example of the added claim :
{
"companies": [
{
"name": "Company A",
"label": "Label A"
},
{
"name": "Company B",
"label": "Label B"
}
]
}To adapt this mapper to your requirements :
- Modify the SQL query in the
fetchCompaniesFromDatabasemethod - Add additional configuration parameters using
ProviderConfigProperty, if needed
Contributions are welcome ! If you want to report an issue or suggest feature, feel free to open an issue or submit a pull request