Securing React Apps with Keycloak: A Comprehensive Guide
· ☕ 3 min read
· ✍️ Dinesh Arora
While there are a variety of authentication services available, including Firebase Authentication and Auth0, there may be situations in your project where you require greater flexibility and control over your user management and authorization with advanced features.
In such cases, Keycloak is an ideal choice as it offers a wide range of features out of the box. Keycloak includes built-in support for OpenID Connect and SAML 2.0, as well as integrations with popular social networks like Google, GitHub, Facebook, and Twitter.
Let’s take a look at how to create a login page using React and keycloak. Note We will not go over how to install keycloak. You can view the installation of keycloak here
Step 1: Install Keycloak JavaScript adapter for React
You can install the Keycloak JavaScript adapter for React using npm. In your project directory, run the following command:
1
npminstall@react-keycloak/webkeycloak-js
Step 2: Set up Keycloak instance
You need to set up a Keycloak instance in your React application. You can do this by creating a Keycloak configuration file with the following code:
Replace the url, realm, and clientId values with your Keycloak server URL, realm name, and client ID.
Step 3: Wrap the app with KeycloakProvider
Wrap your React application with the KeycloakProvider component to provide the Keycloak context to your app. You can do this by adding the following code to your index.js file:
Create a new component for the login page. This component should contain a form with two input fields for the username and password, and a submit button to submit the form. You can use the following code as a starting point:
importReact,{useState}from"react";import{useKeycloak}from"@react-keycloak/web";functionLoginPage(){const{keycloak}=useKeycloak();const[username,setUsername]=useState("");const[password,setPassword]=useState("");consthandleSubmit=async(event)=>{event.preventDefault();try{awaitkeycloak.login({username,password,});}catch(error){console.error("Failed to log in",error);}};return(<formonSubmit={handleSubmit}><inputtype="text"placeholder="Username"value={username}onChange={(event)=>setUsername(event.target.value)}/><inputtype="password"placeholder="Password"value={password}onChange={(event)=>setPassword(event.target.value)}/><buttontype="submit">Login</button></form>);}exportdefaultLoginPage;
Step 5: Use the login page component
You can use the login page component in your main component or any other component in your app. You can also add a link to the login page in your app navigation. Here’s an example of how to use the login page component in your main component: