Skip to content

Iteam1337/keycloak-react

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

keycloak-react

A simple Keycloak integration for React applications.

Installation

npm install keycloak-react

Note: For server-side implementation, use the keycloak-koa package.

Quick Start

1. Setup AuthProvider

// 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>
  );
}

3. Handle Callback

// 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>;
}

4. Protected Content

// 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>
  );
}

API Reference

AuthProvider

<AuthProvider config={authConfig}>
  {children}
</AuthProvider>

Props:

  • config: Configuration object
    • keycloakUrl: 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)

useAuth()

const { user, loading, login, logout, handleCallback } = useAuth();

Returns:

  • user: Current user object or null
  • loading: Boolean for auth state loading
  • login(): Function to initiate login
  • logout(): Function to log out
  • handleCallback(code, redirectUri): Function to handle OAuth callback

ProtectedRoute

<ProtectedRoute redirectTo="/">
  <ProtectedContent />
</ProtectedRoute>

Props:

  • children: Components to render when authenticated
  • redirectTo: Redirect path when not authenticated (optional, defaults to '/')

Server Integration

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 tokens
  • GET /api/user - Get current user info
  • GET /api/logout - Clear session

Advanced Usage

For more complex scenarios like role-based access control, custom login flows, or token refresh strategies, see the keycloak-koa documentation.

License

MIT

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published