This library aims to simplify the integration of Keycloak with NestJS applications. It provides a basic interface, provider and server actions to help you manage the authentication and authorization of applications
npm install queicloco-nextjs
Create a provider to wrap your application with the AuthProvider
component. The AuthProvider
component will manage the authentication and authorization of the application.
// providers.tsx
"use client";
import {PropsWithChildren, Suspense} from "react";
import {AuthProvider, AuthProviderProps} from "queicloco-nextjs";
const keycloakConfig = {
url: process.env.NEXT_PUBLIC_KEYCLOAK_URL!,
realm: process.env.NEXT_PUBLIC_KEYCLOAK_REALM!,
clientId: process.env.NEXT_PUBLIC_KEYCLOAK_CLIENT_ID!,
};
export function Providers({children}: PropsWithChildren) {
const authProps: Omit<AuthProviderProps, "children"> = {
config: keycloakConfig,
profile: (
{username, firstName, lastName, email}, //KeycloakProfile,
{realm_access, resource_access, sub} //KeycloakTokenParsed,
) => {
return {
id: sub,
username,
firstName,
lastName,
email,
realm_access,
resource_access,
};
}
,
}
;
return (
<AuthProvider {...authProps} >
<Suspense>{children} </Suspense>
</AuthProvider>
);
}
Create a page to handle the login callback from Keycloak. This page will be used to redirect the user to the application after the login process is completed.
// app/auth/callback/page.tsx
import { CallbackPage } from "queicloco-nextjs";
export default CallbackPage;
Create a server side page to get the user profile from the server side. This page will be used to get the user profile from the server side.
import { useServerAuth } from "queicloco-nextjs/server";
import Link from "next/link";
export default async function Page() {
const { profile } = await useServerAuth();
return (
<div>
Page {profile?.username}
<Link href={"/"}>Home</Link>
</div>
);
}
Create a client side page to get the user profile from the client side. This page will be used to get the user profile from the client side.
"use client";
import {useAuth} from "queicloco-nextjs";
import Link from "next/link";
export default function Page() {
const {profile} = useAuth();
return (
<div>
Page {profile?.username}
<Link href={"/"}>Home</Link>
</div>
);
}