diff --git a/ui/src/app/api/auth/[...nextauth]/authOptions.ts b/ui/src/app/api/auth/[...nextauth]/authOptions.ts index 78d3c48..08d865d 100644 --- a/ui/src/app/api/auth/[...nextauth]/authOptions.ts +++ b/ui/src/app/api/auth/[...nextauth]/authOptions.ts @@ -18,8 +18,6 @@ export const authOptions: NextAuthOptions = { callbacks: { async jwt({ token, account }: any) { - const nowTimeStamp = Math.floor(Date.now() / 1000); - if (account) { token.decoded = jwtDecode(account.access_token); token.access_token = account.access_token; @@ -29,6 +27,8 @@ export const authOptions: NextAuthOptions = { return token; } + + const nowTimeStamp = Math.floor(Date.now() / 1000); if (nowTimeStamp < token.expires_at) { return token; } diff --git a/ui/src/lib/client.ts b/ui/src/lib/client.ts index f628d9b..2f2a98d 100644 --- a/ui/src/lib/client.ts +++ b/ui/src/lib/client.ts @@ -8,7 +8,7 @@ import { auth } from "../app/api/auth/[...nextauth]/authOptions"; export async function getClient(tenantId: string) { const session = await auth(); - if (!session) redirect("/api/auth/signout"); + if (!session) redirect(`/api/auth/signin?callbackUrl=/`); return new LittleHorseUserTasksApiClient({ baseUrl: process.env.LHUT_API_URL!, diff --git a/ui/src/middleware.ts b/ui/src/middleware.ts index f030dd6..df92906 100644 --- a/ui/src/middleware.ts +++ b/ui/src/middleware.ts @@ -11,6 +11,23 @@ const withAuth = nextAuth(async (req) => { `${baseUrl}/api/auth/signin?callbackUrl=${currentPath}`, ); } + + // Call keycloak to check if token is valid + const keycloakResponse = await fetch( + `${process.env.KEYCLOAK_HOST}/realms/${process.env.KEYCLOAK_REALM}/protocol/openid-connect/userinfo`, + { + headers: { + Authorization: `Bearer ${token.access_token}`, + }, + }, + ); + + if (!keycloakResponse.ok) { + return NextResponse.redirect( + `${baseUrl}/api/auth/signin?callbackUrl=${currentPath}`, + ); + } + // Redirect to tenant after login if (currentPath === "/" && token.decoded.allowed_tenant) { if (token.decoded.realm_access.roles.includes("lh-user-tasks-admin"))