diff --git a/app/api/auth/logout/route.ts b/app/api/auth/logout/route.ts index 505f2916..0ee8cc0d 100644 --- a/app/api/auth/logout/route.ts +++ b/app/api/auth/logout/route.ts @@ -5,20 +5,24 @@ import { authOptions } from '../[...nextauth]/options'; export async function GET() { const session = await getServerSession(authOptions); + const idToken = session?.id_token; - if (session) { - - const idToken = session.id_token; - - const logoutUrl = `${env.AUTH_ISSUER}/protocol/openid-connect/logout?id_token_hint=${idToken}&post_logout_redirect_uri=${encodeURIComponent(env.NEXTAUTH_URL)}`; + if (session && idToken && session.error !== 'RefreshAccessTokenError') { + const logoutUrl = `${env.AUTH_ISSUER}/protocol/openid-connect/logout?${new URLSearchParams( + { + id_token_hint: idToken, + post_logout_redirect_uri: env.NEXTAUTH_URL, + client_id: env.KEYCLOAK_CLIENT_ID, + } + ).toString()}`; return new Response(JSON.stringify({ url: logoutUrl }), { status: 200, headers: { 'Content-Type': 'application/json' }, }); } - - return new Response(JSON.stringify({ url: env.NEXTAUTH_URL }), { + + return new Response(JSON.stringify({ url: `${env.NEXTAUTH_URL}/login` }), { status: 200, headers: { 'Content-Type': 'application/json' }, }); diff --git a/components/SessionGuard.tsx b/components/SessionGuard.tsx index 397b7a16..6fc530a4 100644 --- a/components/SessionGuard.tsx +++ b/components/SessionGuard.tsx @@ -2,20 +2,24 @@ import { ReactNode, useEffect } from 'react'; import { usePathname } from 'next/navigation'; -import { signIn, useSession } from 'next-auth/react'; +import { signIn, signOut, useSession } from 'next-auth/react'; export default function SessionGuard({ children }: { children: ReactNode }) { const { data } = useSession(); - const pathname = usePathname(); useEffect(() => { - if ( - data?.error === 'RefreshAccessTokenError' && - pathname.includes('dashboard') - ) { - signIn('keycloak'); - } + if (data?.error !== 'RefreshAccessTokenError') return; + + const clearExpiredSession = async () => { + await signOut({ redirect: false }); + + if (pathname.includes('dashboard')) { + signIn('keycloak'); + } + }; + + void clearExpiredSession(); }, [data, pathname]); return <>{children};