keycloak-provider
v1.1.0
Published
A modern React provider and hook for seamless Keycloak integration with built-in RBAC support.
Downloads
777
Readme
Keycloak Provider for React
A lightweight, modern React library for integrating Keycloak authentication and Role-Based Access Control (RBAC) into your applications.
Features
- Modern Hooks: Use
useKeycloak()to access authentication state anywhere. - Functional Components: Built with React Hooks for better performance and smaller bundle size.
- Protected Routes: Easily wrap your routes with
<ProtectedRoute />to enforce authentication. - Automatic Token Refresh: Seamlessly handles silent token refreshes in the background.
- Built-in RBAC Support: Simple helpers for realm and resource role checks.
- TypeScript Ready: Full type definitions included for a better developer experience.
Installation
npm install keycloak-providerQuick Start
1. Setup the Provider
Wrap your application with KeycloakAuthProvider at the top level.
import React from 'react';
import { KeycloakAuthProvider } from 'keycloak-provider';
const keycloakConfig = {
url: 'https://your-keycloak-server.com/auth',
realm: 'your-realm',
clientId: 'your-client-id'
};
function App() {
return (
<KeycloakAuthProvider keycloakConfig={keycloakConfig}>
<Main />
</KeycloakAuthProvider>
);
}2. Using the useKeycloak Hook
Access the Keycloak instance and authentication status in any functional component.
import { useKeycloak } from 'keycloak-provider';
function Profile() {
const { keycloak, authenticated } = useKeycloak();
if (!authenticated) return <div>Not logged in</div>;
return (
<div>
<h1>Welcome, {keycloak.tokenParsed.preferred_username}</h1>
<button onClick={() => keycloak.logout()}>Logout</button>
</div>
);
}3. Protecting Routes
Use the ProtectedRoute component to restrict access to specific parts of your app.
import { ProtectedRoute } from 'keycloak-provider';
function Dashboard() {
return (
<ProtectedRoute>
<div>This is a secret dashboard!</div>
</ProtectedRoute>
);
}4. Role-Based Access Control (RBAC)
Check for roles using built-in helpers.
import { useKeycloak, hasRealmRole } from 'keycloak-provider';
function AdminPanel() {
const { keycloak } = useKeycloak();
if (!hasRealmRole(keycloak, 'admin')) {
return <div>Access Denied</div>;
}
return <div>Welcome, Administrator</div>;
}API Reference
KeycloakAuthProvider
keycloakConfig: Object containing your Keycloak configuration.initOptions: (Optional) Options passed tokeycloak.init().loadingComponent: (Optional) Custom component to show while Keycloak is initializing.onTokens: (Optional) Callback triggered when tokens are received or refreshed.
useKeycloak()
Returns an object:
keycloak: The Keycloak instance.authenticated: Boolean status.initialized: Boolean indicating if initialization is complete.
License
ISC
