A simple Keycloak integration for React applications.
npm install keycloak-react
Note: For server-side implementation, use the keycloak-koa package.
// App.jsx
import React from 'react';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import { AuthProvider, ProtectedRoute } from 'keycloak-react';
const App = () => {
const authConfig = {
keycloakUrl: 'https://auth.example.com/realms/my-realm',
clientId: 'my-client',
apiUrl: '/api' // Optional
};
return (
<AuthProvider config={authConfig}>
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/callback" element={<Callback />} />
<Route path="/dashboard" element={
<ProtectedRoute>
<Dashboard />
</ProtectedRoute>
} />
</Routes>
</BrowserRouter>
</AuthProvider>
);
};
### 2. Login Button
```jsx
// Home.jsx
import { useAuth } from 'keycloak-react';
function Home() {
const { user, login, loading } = useAuth();
if (loading) return <div>Loading...</div>;
return (
<div>
<h1>Welcome</h1>
{!user && <button onClick={login}>Login</button>}
{user && <p>Hello, {user.name}!</p>}
</div>
);
}
// Callback.jsx
import { useEffect } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { useAuth } from 'keycloak-react';
function Callback() {
const navigate = useNavigate();
const [searchParams] = useSearchParams();
const { handleCallback } = useAuth();
useEffect(() => {
const code = searchParams.get('code');
if (code) {
handleCallback(code)
.then(() => navigate('/dashboard'))
.catch(err => console.error(err));
}
}, []);
return <div>Authenticating...</div>;
}
// Dashboard.jsx
import { useAuth } from 'keycloak-react';
function Dashboard() {
const { user, logout } = useAuth();
return (
<div>
<h1>Dashboard</h1>
<p>Welcome, {user.name}!</p>
<button onClick={logout}>Logout</button>
</div>
);
}
<AuthProvider config={authConfig}>
{children}
</AuthProvider>
Props:
config
: Configuration objectkeycloakUrl
: Keycloak server URL with realm (required)clientId
: Client ID (required)apiUrl
: API base URL (optional, defaults to '/api')redirectUri
: Redirect URI (optional, defaults to${window.location.origin}/callback
)
const { user, loading, login, logout, handleCallback } = useAuth();
Returns:
user
: Current user object or nullloading
: Boolean for auth state loadinglogin()
: Function to initiate loginlogout()
: Function to log outhandleCallback(code, redirectUri)
: Function to handle OAuth callback
<ProtectedRoute redirectTo="/">
<ProtectedContent />
</ProtectedRoute>
Props:
children
: Components to render when authenticatedredirectTo
: Redirect path when not authenticated (optional, defaults to '/')
This library requires a backend server to handle token exchange and session management. We recommend using keycloak-koa for this purpose.
The server needs to implement these endpoints:
POST /api/token
- Exchange authorization code for tokensGET /api/user
- Get current user infoGET /api/logout
- Clear session
For more complex scenarios like role-based access control, custom login flows, or token refresh strategies, see the keycloak-koa documentation.
MIT