Control user access from the identity provider


Here is my problem, I have a realm A and a realm B.
I want to allow my users in realm A to connect to realm B through identity providers. This works fine but now I would like to limit this access. For example, I would like to allow only users in realm A with the access_realm_b role to connect to realm B.
Do you have any idea how I can achieve this?
Maybe with the first broker login flow?

Here is a first functional solution I don’t know if it’s the best way to do it :
Add a script execution.

  1. Create new authentication flow :
  2. Add your logic with the script
// import enum for error lookup
AuthenticationFlowError = Java.type("org.keycloak.authentication.AuthenticationFlowError");

 * An example authenticate function.
 * The following variables are available for convenience:
 * user - current user {@see org.keycloak.models.UserModel}
 * realm - current realm {@see org.keycloak.models.RealmModel}
 * session - current KeycloakSession {@see org.keycloak.models.KeycloakSession}
 * httpRequest - current HttpRequest {@see org.jboss.resteasy.spi.HttpRequest}
 * script - current script {@see org.keycloak.models.ScriptModel}
 * authenticationSession - current authentication session {@see org.keycloak.sessions.AuthenticationSessionModel}
 * LOG - current logger {@see org.jboss.logging.Logger}
 * You one can extract current http request headers via:
 * httpRequest.getHttpHeaders().getHeaderString("Forwarded")
 * @param context {@see org.keycloak.authentication.AuthenticationFlowContext}
function authenticate(context) {

    var username = user ? user.username : "anonymous"; + " trace auth for: " + username);
    user.getRealmRoleMappings().forEach(function(roleModel) { + " role = : " + roleModel.getName());
    var role = realm.getRole("realm_b");
    if(!user.hasRole(role)){ + " trace auth for: " + "has role true !");
         session.users().removeUser(realm, user);
    var authShouldFail = false;
    if (authShouldFail) {



Then in the parameters of your identity-provider, you must choose your new flow for the Post Login Flow parameter.

I first tried to add my script in the “First Broker Login” flow but at this time my user has not yet retrieved his roles that I configured in the Mappers of my Idenity provider.
I may have ordered it in the flow, I will continue my tests.
After using the script I see an error in my logs :

[stderr] (default task-21) Warning: Nashorn engine is planned to be removed from a future JDK release

I don’t know the reason yet.

If you have other solutions I am always interested.