Files
zitadel/apps/login/src/app/(login)/authenticator/set/page.tsx
T
Max PeintnerandGitHub 9e1b85fa91 fix(login): forward login_hint to the external IdP (#12760)
# Which Problems Are Solved

Login V2 never forwards the OIDC `login_hint` to an external identity
provider. The user enters their identifier once at ZITADEL, is
redirected to the IdP, and has to type it again because the IdP's
authorize request contains no `login_hint`. Login V1 has done this since
#6899 (`sessionParamsFromAuthRequest`), and the backend half for V2
exists since #11552 (`RedirectURLs.login_hint` on
`StartIdentityProviderIntent`), but none of the three places in the
login app that start an IdP intent set it.

# How the Problems Are Solved

Every call to `startIdentityProviderFlow` now sets `urls.loginHint`,
mirroring the priority Login V1 uses:

- `sendLoginname`: when the user is already known and linked to exactly
one IdP, the hint is the username the IdP knows the user by
(`IDPLink.userName`), falling back to the typed login name (with the org
domain suffix re-attached). When an org's single active IdP triggers the
redirect, the hint is the login name.
- `handleOIDCFlowInitiation`: when the auth request selects an IdP via
`urn:zitadel:iam:org:idp🆔<id>`, the hint is `authRequest.loginHint`.
- `redirectToIdp` (the user clicks an IdP button): `SignInWithIdp` gets
an optional `loginHint` prop rendered as a hidden form field. The
loginname page passes the login name it was prefilled with from
`login_hint`; the authenticator setup page passes the session's login
name when linking an IdP to an existing user.

Unit tests cover all three call sites, including the linked-username
priority and the empty-hint case.

Closes #12080
Based on #12683 by @aarontraynor
2026-09-17 16:20:47 +03:00

202 lines
6.5 KiB
TypeScript

import { Alert } from "@/components/alert";
import { BackButton } from "@/components/back-button";
import { ChooseAuthenticatorToSetup } from "@/components/choose-authenticator-to-setup";
import { DynamicTheme } from "@/components/dynamic-theme";
import { SignInWithIdp } from "@/components/sign-in-with-idp";
import { Translated } from "@/components/translated";
import { UserAvatar } from "@/components/user-avatar";
import { getSessionCookieById } from "@/lib/cookies";
import { getServiceConfig } from "@/lib/service-url";
import { loadMostRecentSession } from "@/lib/session";
import { checkUserVerification } from "@/lib/verify-helper";
import {
getActiveIdentityProviders,
getBrandingSettings,
getLoginSettings,
getSession,
getUserByID,
listAuthenticationMethodTypes,
} from "@/lib/zitadel";
import { Session } from "@zitadel/proto/zitadel/session/v2/session_pb";
// import { getLocale } from "next-intl/server";
import { Metadata } from "next";
import { getTranslations } from "next-intl/server";
import { headers } from "next/headers";
import { redirect } from "next/navigation";
export async function generateMetadata(): Promise<Metadata> {
const t = await getTranslations("authenticator");
return { title: t("title") };
}
export default async function Page(props: { searchParams: Promise<Record<string | number | symbol, string | undefined>> }) {
const searchParams = await props.searchParams;
const { loginName, requestId, organization, sessionId } = searchParams;
const _headers = await headers();
const { serviceConfig } = getServiceConfig(_headers);
const sessionWithData = sessionId
? await loadSessionById(sessionId, organization)
: await loadSessionByLoginname(loginName, organization);
async function getAuthMethodsAndUser(session?: Session) {
const userId = session?.factors?.user?.id;
if (!userId) {
throw Error("Could not get user id from session");
}
const methods = await listAuthenticationMethodTypes({ serviceConfig, userId });
const user = await getUserByID({ serviceConfig, userId });
const humanUser = user.user?.type.case === "human" ? user.user?.type.value : undefined;
return {
id: session?.id,
factors: session?.factors,
authMethods: methods.authMethodTypes ?? [],
phoneVerified: humanUser?.phone?.isVerified ?? false,
emailVerified: humanUser?.email?.isVerified ?? false,
expirationDate: session?.expirationDate,
};
}
async function loadSessionByLoginname(loginName?: string, organization?: string) {
const session = await loadMostRecentSession({
serviceConfig,
sessionParams: {
loginName,
organization,
},
});
return getAuthMethodsAndUser(session);
}
async function loadSessionById(sessionId: string, organization?: string) {
const recent = await getSessionCookieById({ sessionId, organization });
if (!recent) {
return undefined;
}
const sessionResponse = await getSession({ serviceConfig, sessionId: recent.id, sessionToken: recent.token });
return getAuthMethodsAndUser(sessionResponse.session);
}
if (!sessionWithData || !sessionWithData.factors || !sessionWithData.factors.user) {
return (
<Alert>
<Translated i18nKey="unknownContext" namespace="error" />
</Alert>
);
}
const branding = await getBrandingSettings({ serviceConfig, organization: sessionWithData.factors.user?.organizationId });
const loginSettings = await getLoginSettings({
serviceConfig,
organization: sessionWithData.factors.user?.organizationId,
});
// check if user was verified recently
const isUserVerified = await checkUserVerification(sessionWithData.factors.user?.id);
if (!isUserVerified) {
const params = new URLSearchParams({
loginName: sessionWithData.factors.user.loginName as string,
invite: "true",
send: "true", // set this to true to request a new code immediately
});
if (requestId) {
params.append("requestId", requestId);
}
if (organization || sessionWithData.factors.user.organizationId) {
params.append("organization", organization ?? (sessionWithData.factors.user.organizationId as string));
}
redirect(`/verify?` + params);
}
const { identityProviders } = await getActiveIdentityProviders({
serviceConfig,
orgId: sessionWithData.factors?.user?.organizationId,
linking_allowed: true,
});
const params = new URLSearchParams({
initial: "true", // defines that a code is not required and is therefore not shown in the UI
});
if (sessionWithData.factors?.user?.loginName) {
params.set("loginName", sessionWithData.factors?.user?.loginName);
}
if (sessionWithData.factors?.user?.organizationId) {
params.set("organization", sessionWithData.factors?.user?.organizationId);
}
if (requestId) {
params.set("requestId", requestId);
}
return (
<DynamicTheme branding={branding}>
<div className="flex flex-col space-y-4">
<h1>
<Translated i18nKey="title" namespace="authenticator" />
</h1>
<p className="ztdl-p">
<Translated i18nKey="description" namespace="authenticator" />
</p>
<UserAvatar
loginName={sessionWithData.factors?.user?.loginName}
displayName={sessionWithData.factors?.user?.displayName}
showDropdown
searchParams={searchParams}
></UserAvatar>
</div>
<div className="w-full">
{loginSettings && (
<ChooseAuthenticatorToSetup
authMethods={sessionWithData.authMethods}
loginSettings={loginSettings}
params={params}
></ChooseAuthenticatorToSetup>
)}
{loginSettings?.allowExternalIdp && !!identityProviders.length && (
<>
<div className="flex flex-col py-3">
<p className="ztdl-p text-center">
<Translated i18nKey="linkWithIDP" namespace="authenticator" />
</p>
</div>
<SignInWithIdp
showLabel={false}
identityProviders={identityProviders}
requestId={requestId}
organization={sessionWithData.factors?.user?.organizationId}
sessionId={sessionWithData.id} // tell the callback function to link the IDP
loginHint={sessionWithData.factors?.user?.loginName}
></SignInWithIdp>
</>
)}
<div className="mt-8 flex w-full flex-row items-center">
<BackButton />
<span className="flex-grow"></span>
</div>
</div>
</DynamicTheme>
);
}