This project demonstrates how to integrate Keycloak authentication with a React Single Page Application (SPA) built using Vite, TypeScript, and React.
This application provides a minimal setup for implementing secure user authentication and authorization in a React application using Keycloak. It demonstrates:
- User authentication with Keycloak
- Retrieving and displaying user information
- Managing authentication state with React Context
- Type-safe integration with TypeScript
- 🔐 Secure authentication using Keycloak
- 🔄 Automatic login redirection
- 👤 User profile information display
- 🚪 Logout functionality
- 📦 Modern React with TypeScript
- Node.js (v22 or newer)
- A running Keycloak server instance
A sample Keycloak client configuration can be found in the extra/react.json file. You can use this as a reference when setting up your Keycloak client.
- Clone this repository
- Install dependencies:
npm install
- Create a
.envfile in the root directory with the following variables:VITE_KEYCLOAK_URL=https://your-keycloak-server/auth VITE_KEYCLOAK_REALM=your-realm VITE_KEYCLOAK_CLIENT_ID=your-client-id
npm run devThis starts the development server with hot module replacement (HMR).
npm run buildnpm run previewsrc/KeycloakProvider.tsx- Context provider that handles Keycloak authenticationsrc/App.tsx- Main application component displaying user informationsrc/main.tsx- Application entry point
- The application initializes Keycloak in the
KeycloakProvidercomponent - Users are automatically redirected to the Keycloak login page if not authenticated
- After successful authentication, user information is extracted from the Keycloak token
- The application displays user details and provides a logout option
The current implementation uses the login-required mode, which automatically redirects unauthenticated users to the login page. To change this behavior, modify the onLoad parameter in the keycloak.init() method in KeycloakProvider.tsx.
You can implement role-based access control by checking the user's roles from the Keycloak token. The application already extracts role information from the token.
- Initialization Issues: Ensure your Keycloak server is running and accessible
- Authentication Failures: Verify that your realm, client ID, and URLs are correctly configured
- Token Parsing Errors: Check that your client has the correct protocol mappers enabled in Keycloak
This project is open source and available under the MIT License.