Skip to main content
Redhat Developers  Logo
  • Products

    Featured

    • Red Hat Enterprise Linux
      Red Hat Enterprise Linux Icon
    • Red Hat OpenShift AI
      Red Hat OpenShift AI
    • Red Hat Enterprise Linux AI
      Linux icon inside of a brain
    • Image mode for Red Hat Enterprise Linux
      RHEL image mode
    • Red Hat OpenShift
      Openshift icon
    • Red Hat Ansible Automation Platform
      Ansible icon
    • Red Hat Developer Hub
      Developer Hub
    • View All Red Hat Products
    • Linux

      • Red Hat Enterprise Linux
      • Image mode for Red Hat Enterprise Linux
      • Red Hat Universal Base Images (UBI)
    • Java runtimes & frameworks

      • JBoss Enterprise Application Platform
      • Red Hat build of OpenJDK
    • Kubernetes

      • Red Hat OpenShift
      • Microsoft Azure Red Hat OpenShift
      • Red Hat OpenShift Virtualization
      • Red Hat OpenShift Lightspeed
    • Integration & App Connectivity

      • Red Hat Build of Apache Camel
      • Red Hat Service Interconnect
      • Red Hat Connectivity Link
    • AI/ML

      • Red Hat OpenShift AI
      • Red Hat Enterprise Linux AI
    • Automation

      • Red Hat Ansible Automation Platform
      • Red Hat Ansible Lightspeed
    • Developer tools

      • Red Hat Trusted Software Supply Chain
      • Podman Desktop
      • Red Hat OpenShift Dev Spaces
    • Developer Sandbox

      Developer Sandbox
      Try Red Hat products and technologies without setup or configuration fees for 30 days with this shared Openshift and Kubernetes cluster.
    • Try at no cost
  • Technologies

    Featured

    • AI/ML
      AI/ML Icon
    • Linux
      Linux Icon
    • Kubernetes
      Cloud icon
    • Automation
      Automation Icon showing arrows moving in a circle around a gear
    • View All Technologies
    • Programming Languages & Frameworks

      • Java
      • Python
      • JavaScript
    • System Design & Architecture

      • Red Hat architecture and design patterns
      • Microservices
      • Event-Driven Architecture
      • Databases
    • Developer Productivity

      • Developer productivity
      • Developer Tools
      • GitOps
    • Secure Development & Architectures

      • Security
      • Secure coding
    • Platform Engineering

      • DevOps
      • DevSecOps
      • Ansible automation for applications and services
    • Automated Data Processing

      • AI/ML
      • Data Science
      • Apache Kafka on Kubernetes
      • View All Technologies
    • Start exploring in the Developer Sandbox for free

      sandbox graphic
      Try Red Hat's products and technologies without setup or configuration.
    • Try at no cost
  • Learn

    Featured

    • Kubernetes & Cloud Native
      Openshift icon
    • Linux
      Rhel icon
    • Automation
      Ansible cloud icon
    • Java
      Java icon
    • AI/ML
      AI/ML Icon
    • View All Learning Resources

    E-Books

    • GitOps Cookbook
    • Podman in Action
    • Kubernetes Operators
    • The Path to GitOps
    • View All E-books

    Cheat Sheets

    • Linux Commands
    • Bash Commands
    • Git
    • systemd Commands
    • View All Cheat Sheets

    Documentation

    • API Catalog
    • Product Documentation
    • Legacy Documentation
    • Red Hat Learning

      Learning image
      Boost your technical skills to expert-level with the help of interactive lessons offered by various Red Hat Learning programs.
    • Explore Red Hat Learning
  • Developer Sandbox

    Developer Sandbox

    • Access Red Hat’s products and technologies without setup or configuration, and start developing quicker than ever before with our new, no-cost sandbox environments.
    • Explore Developer Sandbox

    Featured Developer Sandbox activities

    • Get started with your Developer Sandbox
    • OpenShift virtualization and application modernization using the Developer Sandbox
    • Explore all Developer Sandbox activities

    Ready to start developing apps?

    • Try at no cost
  • Blog
  • Events
  • Videos

How to restrict user authentication in Keycloak during identity brokering

December 30, 2020
Siddhartha De
Related topics:
SecurityLinux

Share:

    As per the design, Keycloak imports all users into its local database if the users are authenticated via any third-party identity provider (e.g., Google, Facebook, or Okta). But what if users authenticated through the third-party identity provider have to be restricted—or be allowed only limited access—to applications that are federated with Keycloak? Here's how you do it.

    You first develop a custom authenticator, which will disable the user if the third-party authenticated user is beyond the known list, and place the authenticator in the First Broker Login authentication flow.

    Note: This article assumes that you are familiar with Keycloak and Maven. Keycloak is an open source identity and access management (IAM) tool and is the upstream project for Red Hat's single sign-on (SSO) tools. Many developers use Keycloak or Red Hat's SSO tools for enterprise security in production environments.

    Creating a custom authenticator with Keycloak

    Keycloak provides an authentication service provider interface (SPI) that we'll use to write a new custom authenticator. As described in the Keycloak documentation, we must do the following when we package the custom authenticator:

    • Package the entire implementation into a single JAR file.
    • Ensure that the JAR contains a file named org.keycloak.authentication.AuthenticatorFactory.
    • Locate the org.keycloak.authentication.AuthenticatorFactory file in the META-INF/services/ directory.
    • Ensure that it lists the fully qualified class name for each AuthenticatorFactory implementation.

    The EnableIfRequire class

    To start, we'll create two classes. The first is EnableIfRequire.java, which enables the user post creation if it exists in the list:

    package com.sid.keycloakauthenticator;
    
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    import java.util.Scanner;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import org.keycloak.authentication.AuthenticationFlowContext;
    import org.keycloak.authentication.authenticators.broker.IdpCreateUserIfUniqueAuthenticator;
    import org.keycloak.authentication.authenticators.broker.util.SerializedBrokeredIdentityContext;
    import org.keycloak.broker.provider.BrokeredIdentityContext;
    import org.keycloak.models.UserModel;
    
    /**
     *
     * @author sidd
     */
    public class EnableIfRequire extends IdpCreateUserIfUniqueAuthenticator {
        //private final List users = Arrays.asList("siddhartha.de@mail.com","sidde3");
        private static List users = new ArrayList();
        
        static{
            File file = new File(System.getProperty("userlist")); //userlist is the reference of file which will hold the list of users
            if (file.exists()) {
                try {
                    Scanner sc = new Scanner(file);
                    sc.useDelimiter(",");
                    while (sc.hasNext()) {
                        users.add(sc.next());
                    }
                }catch (FileNotFoundException ex) {
                    Logger.getLogger(CreateIfRequire.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        
        @Override
        protected void userRegisteredSuccess(AuthenticationFlowContext context, UserModel registeredUser, SerializedBrokeredIdentityContext serializedCtx, BrokeredIdentityContext brokerContext) {
            System.out.println(registeredUser.getUsername()+" User is successfully registered...");
            if(!users.contains(registeredUser.getUsername())){
                registeredUser.setEnabled(false);              //Disable the user if not there in list
            }
            
        }
    }

    The EnableIfRequireFactory class

    Next, we create EnableIfRequireFactory.java, which instantiates the authenticator:

    package com.sid.keycloakauthenticator;
    
    import java.util.ArrayList;
    import java.util.List;
    import org.keycloak.Config;
    import org.keycloak.authentication.Authenticator;
    import org.keycloak.authentication.authenticators.broker.IdpCreateUserIfUniqueAuthenticatorFactory;
    import org.keycloak.models.KeycloakSession;
    import org.keycloak.provider.ProviderConfigProperty;
    
    /*
     * @author sid
     */
    public class EnableIfRequireFactory extends IdpCreateUserIfUniqueAuthenticatorFactory {
    
        public static final String PROVIDER_ID = "idp-enable-user-if-require";
        static CreateIfRequire SINGLETON = new CreateIfRequire();
    
        public static final String REQUIRE_PASSWORD_UPDATE_AFTER_REGISTRATION = "require.password.update.after.registration";
    
        @Override
        public Authenticator create(KeycloakSession session) {
            return SINGLETON;
        }
    
        @Override
        public void init(Config.Scope config) {
    
        }
    
        @Override
        public String getId() {
            return PROVIDER_ID;
        }
    
        @Override
        public String getDisplayType() {
            return "Enable User When Require";
        }
    
        @Override
        public String getHelpText() {
            return "Enable user when require";
        }
    
        private static final List configProperties = new ArrayList();
    
        static {
            ProviderConfigProperty property;
            property = new ProviderConfigProperty();
            property.setName(REQUIRE_PASSWORD_UPDATE_AFTER_REGISTRATION);
            property.setLabel("Require Password Update");
            property.setType(ProviderConfigProperty.BOOLEAN_TYPE);
            property.setHelpText("You are required to update password when user will be created");
            configProperties.add(property);
        }
    
        @Override
        public List getConfigProperties() {
            return configProperties;
        }
    }
    

    Organize and compile the Keycloak custom authenticator

    In this section, we'll use Maven to organize the mobile authentication project and compile our two new classes.

    Set up the project

    Execute the following command to create a project using Maven:

    mvn archetype:generate -DgroupId=com.sid.keycloakauthenticator -DartifactId=keycloak-authenticator -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
    

    Place both of the classes that we've just created in the src/main/java/com/sid/keycloakauthenticator path.

    Now, create a file named org.keycloak.authentication.AuthenticatorFactory at src/main/resources/META-INF/services. Add an entry for the new AuthenticationFactory: com.sid.keycloakauthenticator.EnableIfRequireFactory.

    Resolve the project dependencies

    The Keycloak authentication module is a private SPI, so you are required to use the MANIFEST.MF to resolve dependencies. Make the following entry in the MANIFEST.MF at the line src/main/resources/META-INF:

    Dependencies: org.keycloak.keycloak-server-spi-private, org.keycloak.keycloak-services, org.keycloak.keycloak-core, org.keycloak.keycloak-server-spi
    

    You can now edit the Maven pom.xml to add the following dependencies:

            <dependency>
    	   <groupId>org.keycloak</groupId>
    	   <artifactId>keycloak-core</artifactId>
    	   <version>4.8.3.Final</version>
    	   <scope>provided</scope>
    	</dependency>
    	<dependency>
    	   <groupId>org.keycloak</groupId>
    	   <artifactId>keycloak-server-spi</artifactId>
    	   <version>4.8.3.Final</version>
    	   <scope>provided</scope>
    	</dependency>
    	<dependency>
    	   <groupId>org.keycloak</groupId>
    	   <artifactId>keycloak-server-spi-private</artifactId>
    	   <version>4.8.3.Final</version>
    	   <scope>provided</scope>
    	</dependency>
    	<dependency>
    	   <groupId>org.jboss.logging</groupId>
    	   <artifactId>jboss-logging</artifactId>
    	   <version>3.4.0.Final</version>
    	   <scope>provided</scope>
    	</dependency>
    	<dependency>
    	   <groupId>org.keycloak</groupId>
    	   <artifactId>keycloak-services</artifactId>
    	   <version>4.8.3.Final</version>
    	   <scope>provided</scope>
    	</dependency>
    

    Build and deploy the project

    Execute the following command to build the project:

    mvn clean install
    

    This command generates output in the keycloak-authenticator-1.0-SNAPSHOT.jar target folder. Keycloak ships bundled with WildFly, so you can use the jboss-cli interface and the following command to deploy the JAR:

    deploy /path/to/keycloak-authenticator-1.0-SNAPSHOT.jar
    

    Configure the custom authentication flow

    After you've successfully deployed the authenticator JAR, you will configure the authentication flow. Here's how to configure a custom flow in Keycloak:

    1. Log into the Keycloak management console, select the realm where you want to configure the custom mobile authenticator, and click on Authentication in the left-side panel.
    2. In the Flow tab, select First Broker Login from the drop-down list.
    3. Click the Copy button and name the flow; for example, CustomBrokerFlow.
    4. Click Add Execution and select Enable User When Require in the provider drop-down list
    5. Place the executor just after Create User If Unique
    6. Now, this authentication flow can be used against the associated identity provider's First Login Flow.
    Last updated: December 29, 2020

    Recent Posts

    • How Trilio secures OpenShift virtual machines and containers

    • How to implement observability with Node.js and Llama Stack

    • How to encrypt RHEL images for Azure confidential VMs

    • How to manage RHEL virtual machines with Podman Desktop

    • Speech-to-text with Whisper and Red Hat AI Inference Server

    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Products

    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform

    Build

    • Developer Sandbox
    • Developer Tools
    • Interactive Tutorials
    • API Catalog

    Quicklinks

    • Learning Resources
    • E-books
    • Cheat Sheets
    • Blog
    • Events
    • Newsletter

    Communicate

    • About us
    • Contact sales
    • Find a partner
    • Report a website issue
    • Site Status Dashboard
    • Report a security problem

    RED HAT DEVELOPER

    Build here. Go anywhere.

    We serve the builders. The problem solvers who create careers with code.

    Join us if you’re a developer, software engineer, web designer, front-end designer, UX designer, computer scientist, architect, tester, product manager, project manager or team lead.

    Sign me up

    Red Hat legal and privacy links

    • About Red Hat
    • Jobs
    • Events
    • Locations
    • Contact Red Hat
    • Red Hat Blog
    • Inclusion at Red Hat
    • Cool Stuff Store
    • Red Hat Summit

    Red Hat legal and privacy links

    • Privacy statement
    • Terms of use
    • All policies and guidelines
    • Digital accessibility

    Report a website issue