fix(auth): resolve Keycloak OIDC issuer mismatch and API proxy routing
Some checks failed
CI Pipeline / Backend Build & Test (pull_request) Successful in 49s
CI Pipeline / Frontend Lint, Test & Build (pull_request) Failing after 26s
CI Pipeline / Infrastructure Validation (pull_request) Successful in 4s

- Bypass NextAuth OIDC discovery with explicit token/userinfo endpoints using internal Docker DNS, avoiding 'issuer string did not match' errors.
- Fix next.config.ts API route interception that incorrectly forwarded NextAuth routes to backend by using 'fallback' rewrites.
- Add 'Use different credentials' button to login page and AuthGuard for clearing stale sessions.
This commit is contained in:
WorkClub Automation
2026-03-09 14:21:03 +01:00
parent a8730245b2
commit 1322def2ea
5 changed files with 65 additions and 14 deletions

View File

@@ -89,6 +89,8 @@ services:
KEYCLOAK_CLIENT_ID: "workclub-app"
KEYCLOAK_CLIENT_SECRET: "dev-secret-workclub-api-change-in-production"
KEYCLOAK_ISSUER: "http://localhost:8080/realms/workclub"
KEYCLOAK_ISSUER_INTERNAL: "http://keycloak:8080/realms/workclub"
NEXT_PUBLIC_KEYCLOAK_ISSUER: "http://localhost:8080/realms/workclub"
ports:
- "3000:3000"
volumes:

View File

@@ -3,13 +3,17 @@ import type { NextConfig } from "next";
const nextConfig: NextConfig = {
output: 'standalone',
async rewrites() {
const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:5001';
return [
const apiUrl = process.env.API_INTERNAL_URL || process.env.NEXT_PUBLIC_API_URL || 'http://localhost:5001';
return {
beforeFiles: [],
afterFiles: [],
fallback: [
{
source: '/api/:path*',
destination: `${apiUrl}/api/:path*`,
},
];
],
};
},
};

View File

@@ -1,16 +1,17 @@
'use client';
import { useEffect } from 'react';
import { signIn, useSession } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card';
import { signIn, signOut, useSession } from 'next-auth/react';
import { useRouter, useSearchParams } from 'next/navigation';
import { Card, CardHeader, CardTitle, CardContent, CardFooter } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
export default function LoginPage() {
const { status } = useSession();
const router = useRouter();
const searchParams = useSearchParams();
const hasError = searchParams.get('error') || searchParams.get('callbackUrl');
// Redirect to dashboard if already authenticated
useEffect(() => {
if (status === 'authenticated') {
router.push('/dashboard');
@@ -21,17 +22,34 @@ export default function LoginPage() {
signIn('keycloak', { callbackUrl: '/dashboard' });
};
const handleSwitchAccount = () => {
const keycloakLogoutUrl = `${process.env.NEXT_PUBLIC_KEYCLOAK_ISSUER || 'http://localhost:8080/realms/workclub'}/protocol/openid-connect/logout?redirect_uri=${encodeURIComponent(window.location.origin + '/login')}`;
signOut({ redirect: false }).then(() => {
window.location.href = keycloakLogoutUrl;
});
};
return (
<div className="flex items-center justify-center min-h-screen bg-gray-50">
<Card className="w-96">
<CardHeader>
<CardTitle className="text-2xl text-center">WorkClub Manager</CardTitle>
</CardHeader>
<CardContent>
<CardContent className="space-y-3">
<Button onClick={handleSignIn} className="w-full">
Sign in with Keycloak
</Button>
<Button variant="outline" onClick={handleSwitchAccount} className="w-full">
Use different credentials
</Button>
</CardContent>
{hasError && (
<CardFooter>
<p className="text-sm text-muted-foreground text-center w-full">
Having trouble? Try &quot;Use different credentials&quot; to clear your session.
</p>
</CardFooter>
)}
</Card>
</div>
);

View File

@@ -19,12 +19,26 @@ declare module "next-auth" {
}
}
// In Docker, the Next.js server reaches Keycloak via internal hostname
// (keycloak:8080) but the browser uses localhost:8080. Explicit endpoint
// URLs bypass OIDC discovery, avoiding issuer mismatch validation errors.
const issuerPublic = process.env.KEYCLOAK_ISSUER!
const issuerInternal = process.env.KEYCLOAK_ISSUER_INTERNAL || issuerPublic
const oidcPublic = `${issuerPublic}/protocol/openid-connect`
const oidcInternal = `${issuerInternal}/protocol/openid-connect`
export const { handlers, signIn, signOut, auth } = NextAuth({
providers: [
KeycloakProvider({
clientId: process.env.KEYCLOAK_CLIENT_ID!,
clientSecret: process.env.KEYCLOAK_CLIENT_SECRET!,
issuer: process.env.KEYCLOAK_ISSUER!,
issuer: issuerPublic,
authorization: {
url: `${oidcPublic}/auth`,
params: { scope: "openid email profile" },
},
token: `${oidcInternal}/token`,
userinfo: `${oidcInternal}/userinfo`,
})
],
callbacks: {

View File

@@ -1,6 +1,6 @@
'use client';
import { useSession } from 'next-auth/react';
import { useSession, signOut } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import { ReactNode, useEffect } from 'react';
import { useTenant } from '../contexts/tenant-context';
@@ -47,10 +47,23 @@ export function AuthGuard({ children }: { children: ReactNode }) {
}
if (clubs.length === 0 && status === 'authenticated') {
const handleSwitchAccount = () => {
const keycloakLogoutUrl = `${process.env.NEXT_PUBLIC_KEYCLOAK_ISSUER || 'http://localhost:8080/realms/workclub'}/protocol/openid-connect/logout?redirect_uri=${encodeURIComponent(window.location.origin + '/login')}`;
signOut({ redirect: false }).then(() => {
window.location.href = keycloakLogoutUrl;
});
};
return (
<div className="flex flex-col items-center justify-center min-h-screen gap-4">
<h2 className="text-2xl font-bold">No Clubs Found</h2>
<p>Contact admin to get access to a club</p>
<button
onClick={handleSwitchAccount}
className="mt-4 px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-800 rounded-md border border-gray-300 transition-colors"
>
Use different credentials
</button>
</div>
);
}