As you know keycloak we are using to add authentication to applications and secure services with minimum effort. No need to deal with storing users or authenticating users. So, we can also let NEXT.JS integrate with it, by OpenID Connect (OIDC) .
What is OpenID Connect (OIDC)?
OpenID Connect (OIDC) is an identity authentication protocol that is an extension of open authorization (OAuth) 2.0 to standardize the process for authenticating and authorizing users when they sign in to access digital services.
To install OIDC
npm install oidc-client-ts --save
OR we can clone the sample project to test git > oidc-client-ts repository.
git clone https://github.com/authts/oidc-client-ts.git
cd oidc-client-ts
npm install
npm run build
Config with NEXT.JS
Install OIDC and OIDC Context to get Provider for Auth.
npm install react-oidc-context oidc-client-ts --save
Create a keycloak service for oidc config
// keycloak.service.ts
import { User, WebStorageStateStore } from "oidc-client-ts";
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const onSigninCallback = (_user: User | void): void => {
if (typeof window !== "undefined") {
window.history.replaceState({}, document.title, window.location.pathname);
}
};
export const getCurrentUrl = (): string | null => {
if (typeof window !== "undefined") {
return window.location.href;
}
return null;
};
const webStorage = () => {
let storage: Storage | null;
if (typeof window !== "undefined") {
storage = window.localStorage;
} else {
storage = {} as Storage;
}
return storage;
};
const redirectWebOrigin = (): string | null => {
if (typeof window !== "undefined") {
return window.location.origin;
}
return null;
};
const oidcConfig = {
authority: process.env.KEYCLOAK_AUTH_ISSUER_URL,
client_id: process.env.KEYCLOAK_CLIENT_ID,
client_secret: process.env.KEYCLOAK_CLIENT_SECRET_KEY,
redirect_uri: getCurrentUrl(),
userStore: new WebStorageStateStore({ store: webStorage() }),
onSigninCallback,
post_logout_redirect_uri: redirectWebOrigin(),
};
export default oidcConfig;
Create a provider as a client component
"use client";
import { AuthProvider } from "react-oidc-context";
import oidcConfig from "@/services/keycloak.service";
export default function AuthProvider({
children,
}: {
children: React.ReactNode;
}) {
return <AuthProvider {...oidcConfig}>{children}</AuthProvider>;
}
Back to Root layout and past the provider in.
import AuthProvider from "./AuthProvider";
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<AuthProvider>
<html lang="en">
<body>{children}</body>
</html>
</AuthProvider>
);
}