Fix SSO token exchange: restore redirectProxyUrl alongside explicit redirect_uri

authorization.params.redirect_uri fixes the authorization request URI.
redirectProxyUrl fixes the token exchange URI (beta.30 uses it there).
Both are needed. AUTH_URL must now include /api/auth suffix on the server.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Vadym Samoilenko 2026-04-15 15:22:01 +01:00
parent 1950ecc7d6
commit 1b07542a31

View file

@ -4,12 +4,16 @@ import { PrismaAdapter } from "@auth/prisma-adapter";
import { prisma } from "@/lib/prisma";
import type { Role } from "@/generated/prisma/client";
// next-auth v5 beta ignores redirectProxyUrl when building the redirect_uri
// sent to the OAuth provider — it strips the pathname from AUTH_URL and appends
// basePath directly to the origin. We must pass redirect_uri explicitly so the
// /hp-prod-tracker basePath is included in the Microsoft callback URL.
const explicitRedirectUri = process.env.AUTH_URL
? `${process.env.AUTH_URL}/api/auth/callback/microsoft-entra-id`
// AUTH_URL must be the full auth endpoint URL including basePath, e.g.:
// https://optical-dev.oliver.solutions/hp-prod-tracker/api/auth
//
// next-auth v5 beta ignores redirectProxyUrl for the authorization request
// (strips pathname from AUTH_URL) but DOES use it for the token exchange.
// We fix the authorization request via authorization.params.redirect_uri
// and restore redirectProxyUrl so token exchange uses the same URI.
const authUrl = process.env.AUTH_URL; // e.g. https://…/hp-prod-tracker/api/auth
const explicitRedirectUri = authUrl
? `${authUrl}/callback/microsoft-entra-id`
: undefined;
export const { handlers, auth, signIn, signOut } = NextAuth({
@ -26,11 +30,13 @@ export const { handlers, auth, signIn, signOut } = NextAuth({
// Safe for Entra ID — Microsoft verifies organizational emails.
// Required to link SSO accounts to pre-seeded User records by email match.
allowDangerousEmailAccountLinking: true,
// Explicitly set redirect_uri so /hp-prod-tracker basePath is included.
// next-auth v5 beta strips the pathname from AUTH_URL otherwise.
// authorization.params: fixes redirect_uri in the authorization request
// redirectProxyUrl: fixes redirect_uri in the token exchange request
// Both are needed — beta.30 ignores redirectProxyUrl for authorization.
...(explicitRedirectUri && {
authorization: { params: { redirect_uri: explicitRedirectUri } },
}),
redirectProxyUrl: authUrl,
}),
],
session: {