- Install the necessary packages. You'll need the
keycloak-js
package to handle authentication with Keycloak. You can install it by running the following command:
npm install keycloak-js
Create a new file called
keycloak.js
in the root of your project.In
keycloak.js
, you can configure the Keycloak client using theKeycloak
constructor. Here's an example:
import Keycloak from 'keycloak-js';
const keycloak = new Keycloak({
url: 'YOUR_KEYCLOAK_URL',
realm: 'YOUR_REALM',
clientId: 'YOUR_CLIENT_ID',
});
export default keycloak;
Make sure to replace 'YOUR_KEYCLOAK_URL'
, 'YOUR_REALM'
, and 'YOUR_CLIENT_ID'
with the appropriate values for your Keycloak setup.
- In your Next.js
_app.js
file, you can add the Keycloak authentication logic. Here's an example:
import { useEffect } from 'react';
import keycloak from '../keycloak';
function MyApp({ Component, pageProps }) {
useEffect(() => {
keycloak
.init({ onLoad: 'login-required' })
.then((authenticated) => {
if (authenticated) {
console.log('User is authenticated');
} else {
console.log('User is not authenticated');
}
})
.catch((error) => {
console.error('Keycloak initialization error:', error);
});
}, []);
return <Component {...pageProps} />;
}
export default MyApp;
This code initializes the Keycloak client when the app loads and redirects the user to the Keycloak login page if they are not authenticated.
- To protect specific routes with authentication, you can create a custom higher-order component (HOC) that checks if the user is authenticated before rendering the page. Here's an example:
import keycloak from '../keycloak';
export function withAuth(Component) {
return function AuthenticatedComponent(props) {
const { authenticated } = keycloak;
if (!authenticated) {
return <div>Not authenticated</div>; // Redirect to login page
}
return <Component {...props} />;
};
}
You can then wrap your protected pages with the withAuth
Top comments (1)
Great tutorial!