Keycloak is an Open Source software built by
Authentication and Authorization is a repetitive requirement and one of the most important

The requirement
I was looking for an option to execute a custom script. The requirement was pretty simple – assign role based on how

Implementation
One of the strong features of Keycloak is the flexibility to extend the features by either creating Listeners, REST APIs, custom scripts etc. This is definitely a must for applications which needs to leverage a mix of both breeds – readymade solutions plus the ability to extend the functionality.
Social identity provider – Role assignment
With K
This will bring up screen to configure the Identity provider. You will see three tabs on Top of the section. Click Mappers tab and then click Create button.

This should bring up screen to add mapper after user logs in. From the mapper type dropdown select “Hardcoded Role”. The screen content will dynamically change and it will prompt you to select a role. Choose the appropriate role and give a meaningful name to the mapper configuration. Save the configuration and Thats All!!!

With this configuration whenever user logs in using the Social Identity provider, the configured role will be allocated.
Custom Login
In
- Click Authentication link from the left side menu. This should bring up Authentication flows configured in the application.
- Select the Authentication flow used by your application.
- Click Add Execution button available on the right side of the main section. Refer below screen for details.

This should bring up a screen to add a provider. Choose “Script” from the dropdown and click Save. This should result in the new entry being added below the flow configuration you have selected.
- To proceed with the configuration, make sure the required flag for the script is turned on.
- Then click the Actions link and choose Config option. This should bring up the screen to configure script. Enter all the required details and add below code in the scripts section.
AuthenticationFlowError = Java.type("org.keycloak.authentication.AuthenticationFlowError");
function authenticate(context) {
var username = user ? user.username : "anonymous";
var domainRole = session.getContext().getClient().getRole("NAME_OF_DOMAIN_ROLE");
if(domainRole) {
user.grantRole(domainRole);
}
context.success();
}
Few things to note here.
- The role assigned in the above script belongs to the Client Application. You can very well assign a global role as well.
- The script checks if the role is available or not, in case if you misspelled role name or the role is not available, script will silently fail.
Now when user signs up for custom authentication, it will be allocated the domain role configured in the script. Pretty easy, huh 🙂
We have barely scratched the surface of what Keycloak is really capable of.