- Install the required packages:
npm install next-auth keycloak-js
- Create a
pages/_app.js
file with the following code:
import { Provider } from 'next-auth/client';
import { useEffect } from 'react';
import Keycloak from 'keycloak-js';
function MyApp({ Component, pageProps }) {
useEffect(() => {
const keycloakConfig = {
url: 'YOUR_KEYCLOAK_URL',
realm: 'YOUR_REALM',
clientId: 'YOUR_CLIENT_ID',
};
const keycloak = Keycloak(keycloakConfig);
keycloak.init({ onLoad: 'login-required' }).success((authenticated) => {
if (authenticated) {
// If the user is authenticated, render the app
keycloak.loadUserProfile().success((userProfile) => {
// Pass the user's profile to the app
pageProps.user = userProfile;
renderApp();
});
} else {
// If the user is not authenticated, redirect to Keycloak login
keycloak.login();
}
});
function renderApp() {
ReactDOM.render(
<Provider session={pageProps.session}>
<Component {...pageProps} />
</Provider>,
document.getElementById('root')
);
}
return () => {
ReactDOM.unmountComponentAtNode(document.getElementById('root'));
};
}, []);
return null;
}
export default MyApp;
- In your Next.js pages, you can access the user's profile using
useSession
fromnext-auth/client
. For example, inpages/index.js
:
import { useSession } from 'next-auth/client';
export default function Home() {
const [session, loading] = useSession();
if (loading) {
return <div>Loading...</div>;
}
if (!session) {
return null; // Redirecting to Keycloak login
}
return (
<div>
<h1>Welcome, {session.user.name}!</h1>
<button onClick={() => signOut()}>Sign Out</button>
</div>
);
}
Make sure to replace the placeholders YOUR_KEYCLOAK_URL
, YOUR_REALM
, and YOUR_CLIENT_ID
with your actual
Top comments (1)