Skip to main content
Redhat Developers  Logo
  • Products

    Platforms

    • Red Hat Enterprise Linux
      Red Hat Enterprise Linux Icon
    • Red Hat AI
      Red Hat AI
    • Red Hat OpenShift
      Openshift icon
    • Red Hat Ansible Automation Platform
      Ansible icon
    • View All Red Hat Products

    Featured

    • Red Hat build of OpenJDK
    • Red Hat Developer Hub
    • Red Hat JBoss Enterprise Application Platform
    • Red Hat OpenShift Dev Spaces
    • Red Hat OpenShift Local
    • Red Hat 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
    • Automated Data Processing

      • AI/ML
      • Data Science
      • Apache Kafka on Kubernetes
    • Platform Engineering

      • DevOps
      • DevSecOps
      • Ansible automation for applications and services
    • Secure Development & Architectures

      • Security
      • Secure coding
  • Learn

    Featured

    • Kubernetes & Cloud Native
      Openshift icon
    • Linux
      Rhel icon
    • Automation
      Ansible cloud 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

    • Product Documentation
    • API Catalog
    • Legacy Documentation
  • 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

Use mobile numbers for user authentication in Keycloak

October 23, 2020
Siddhartha De
Related topics:
JavaLinuxSecurity
Related products:
Red Hat Single sign-on

Share:

    I recently worked on a project that required using a mobile number for user authentication, instead of the traditional username and password. Almost everyone has a unique mobile number, so the requirement made sense. Our authentication tool is Keycloak, which does not ship with an option for mobile-based authentication. Instead, my team developed a custom authentication executor to meet the requirement.

    In this article, I show you how to use Keycloak's authentication service provider interface (SPI) to write a custom MobileAuthenticator class and then instantiate it with an AuthenticationFactory. I also show you how to package and compile the mobile authentication project using Maven and how to create a custom mobile authentication flow for Keycloak.

    Note: This article assumes that you are familiar with Keycloak, Maven, and Red Hat JBoss Enterprise Application Platform. Keycloak is an open source identity and access management (IAM) tool and is the upstream project for Red Hat Single Sign-On (Red Hat SSO). Many developers use Keycloak or Red Hat SSO 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 MobileAuthenticator class

    To start, we'll create two classes. The first is MobileAuthenticator.java, which performs the authentication:

    package com.sid.keycloakauthenticator;
    import java.util.List;
    import javax.ws.rs.core.MultivaluedMap;
    import org.keycloak.authentication.AuthenticationFlowContext;
    import org.keycloak.authentication.Authenticator;
    import org.keycloak.authentication.authenticators.browser.UsernamePasswordForm;
    import org.keycloak.events.Errors;
    import org.keycloak.services.managers.AuthenticationManager;
    
    import javax.ws.rs.core.Response;
    import org.keycloak.authentication.AuthenticationFlowError;
    import org.keycloak.authentication.authenticators.browser.AbstractUsernameFormAuthenticator;
    import org.keycloak.events.Details;
    import org.keycloak.models.ModelDuplicateException;
    import org.keycloak.models.UserModel;
    import org.keycloak.services.messages.Messages;
    
    /**
     * @author sid
     **/
    public class MobileAuthenticator extends UsernamePasswordForm implements Authenticator {
    
       @Override
       public boolean validateUserAndPassword(AuthenticationFlowContext context, MultivaluedMap inputData) {
    	String username = inputData.getFirst(AuthenticationManager.FORM_USERNAME);
    	if (username == null) {
    	   context.getEvent().error(Errors.USER_NOT_FOUND);
    	   Response challengeResponse = challenge(context, Messages.INVALID_USER);
    	   context.failureChallenge(AuthenticationFlowError.INVALID_USER, challengeResponse);
    	   return false;
    	}
    
    	// remove leading and trailing whitespace
    	username = username.trim();
    	context.getEvent().detail(Details.USERNAME, username);
    	context.getAuthenticationSession().setAuthNote(AbstractUsernameFormAuthenticator.ATTEMPTED_USERNAME, username);
    	UserModel user = null;
    	try {
    	   List users = context.getSession().users().searchForUserByUserAttribute("mobile", username, context.getRealm());
    	   System.out.println(users.get(0).getUsername());
    	   if (users != null && users.size() == 1) {
    		user = users.get(0);
    	   }
    	} catch (ModelDuplicateException mde) {
    	   if (mde.getDuplicateFieldName() != null && mde.getDuplicateFieldName().equals(UserModel.EMAIL)) {
    		setDuplicateUserChallenge(context, Errors.EMAIL_IN_USE, Messages.EMAIL_EXISTS, AuthenticationFlowError.INVALID_USER);
    	   } else {
    		setDuplicateUserChallenge(context, Errors.USERNAME_IN_USE, Messages.USERNAME_EXISTS, AuthenticationFlowError.INVALID_USER);
    	   }
    	   return false;
    	}
    
    	if (invalidUser(context, user)) {
    	   return false;
    	}
    
    	if (!validatePassword(context, user, inputData)) {
    	   return false;
    	}
    
    	if (!enabledUser(context, user)) {
    	   return false;
    	}
    
    	String rememberMe = inputData.getFirst("rememberMe");
    	boolean remember = rememberMe != null && rememberMe.equalsIgnoreCase("on");
    	if (remember) {
    	   context.getAuthenticationSession().setAuthNote(Details.REMEMBER_ME, "true");
    	   context.getEvent().detail(Details.REMEMBER_ME, "true");
    	} else {
    	   context.getAuthenticationSession().removeAuthNote(Details.REMEMBER_ME);
    	}
    	context.setUser(user);
    
    	return true;
       }
    }

    The MobileAuthenticationFactory class

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

    package com.sid.keycloakauthenticator;
    
    import org.keycloak.Config;
    import org.keycloak.authentication.Authenticator;
    import org.keycloak.authentication.authenticators.browser.UsernamePasswordFormFactory;
    import org.keycloak.models.KeycloakSession;
    
    /**
     * @author sid
     **/
    public class MobileAuthenticationFactory extends UsernamePasswordFormFactory {
    
       public static final String PROVIDER_ID = "mobile-authenticator";
       public static final MobileAuthenticator SINGLETON = new MobileAuthenticator();
    
       @Override
       public Authenticator create(KeycloakSession session) {
    	return SINGLETON;
       }
    
       @Override
       public void init(Config.Scope scope) {
       }
    
       @Override
       public String getId() {
    	return PROVIDER_ID;
       }
    
       @Override
       public String getDisplayType() {
    	return "Mobile Based User Form";
       }
    
       @Override
       public String getHelpText() {
    	return "Validates a mobile and password from login form.";
       }
    }
    

    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.MobileAuthenticationFactory.

    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 in into 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 Browser from the drop-down list.
    3. Click the Copy button and name the flow; for example, MobileFlow.
    4. Under MobileFlow Forms, click the Actions hyperlink to add executions.
    5. Save the flow by selecting Mobile Based User Form from the provider list.
    6. Delete the Username Password Form and the OTP Form.

    Conclusion

    That's all there is to setting up mobile-based authentication with Keycloak. Note that for the authentication to be successful, you must ensure that every user has a unique mobile number assigned in their attributes.

    Last updated: January 12, 2024

    Recent Posts

    • How to enable Ansible Lightspeed intelligent assistant

    • Why some agentic AI developers are moving code from Python to Rust

    • Confidential VMs: The core of confidential containers

    • Benchmarking with GuideLLM in air-gapped OpenShift clusters

    • Run Qwen3-Next on vLLM with Red Hat AI: A step-by-step guide

    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
    © 2025 Red Hat

    Red Hat legal and privacy links

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

    Report a website issue