How to configure Keycloak with Nextjs with next-auth for authentication
install next-auth library
create “pages/api/auth/[…nextauth]”.ts:
import NextAuth from 'next-auth';
import KeycloakProvider from 'next-auth/providers/keycloak';export const authOptions = {
providers: [
KeycloakProvider({
clientId: process.env.KEYCLOAK_ID,
clientSecret: process.env.KEYCLOAK_SECRET,
issuer: process.env.KEYCLOAK_ISSUER,
}),
],
};export default NextAuth(authOptions);
Configure Keycloak:
Create an realm for the nextjs app.
Create a client for the nextjs app, configure:
Home URL: http://localhost:3000
Valid redirect URIs: http://localhost:3000/*
This allows Keycloak to redirect back to your URI.
Web origins: http://localhost:3000
In The Credentials in the client setting, find the “Client secret”, then add following to .env in your nextjs app:
KEYCLOAK_ID="[client id]"
KEYCLOAK_SECRET="[secret]"
KEYCLOAK_ISSUER="http://localhost:8080/realms/[REALM-ID]" (replace [REALM-ID] with your realm id
To initiate login:
import { signIn } from 'next-auth/react';// in a button handler
signIn()
and this will redirect to a build-in login page, then click on “login with Keycloak”.
after redirecting back to your app, you can use:
const { data: session } = useSession();
to look at the session data.