mirror of
https://github.com/andwati/zitadel.git
synced 2026-11-19 19:48:45 +00:00
fix(login): fallback for idp login (#10876)
Closes #10671 # Which Problems Are Solved Users with password authentication disabled in their organization were seeing "Username Password not allowed!" error instead of being redirected to their organization's configured Identity Provider. This affected domain discovery and multi-tenancy use cases in Login V2. # How the Problems Are Solved - Updated `redirectUserToIDP` to accept optional `userId` and `organization` parameters - Added fallback logic to check organization-level IDPs via `getActiveIdentityProviders` - Updated all call sites to pass appropriate organization context - Added test coverage for the fallback behavior # Additional Changes - Consolidated duplicate logic by removing `redirectUserToSingleIDPIfAvailable` function, which is now handled by the unified `redirectUserToIDP` function - improved error handling on verification page --------- Co-authored-by: Ramon <[email protected]>
This commit is contained in:
@@ -249,6 +249,7 @@ describe("sendLoginname", () => {
|
||||
authMethodTypes: [AuthenticationMethodType.PASSWORD],
|
||||
});
|
||||
mockListIDPLinks.mockResolvedValue({ result: [] });
|
||||
mockGetActiveIdentityProviders.mockResolvedValue({ identityProviders: [] });
|
||||
|
||||
const result = await sendLoginname({
|
||||
loginName: "[email protected]",
|
||||
@@ -259,6 +260,29 @@ describe("sendLoginname", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("should redirect to organization IDP when password not allowed, no user IDP links, but organization has active IDP", async () => {
|
||||
mockGetLoginSettings.mockResolvedValue({ allowUsernamePassword: false });
|
||||
mockListAuthenticationMethodTypes.mockResolvedValue({
|
||||
authMethodTypes: [AuthenticationMethodType.PASSWORD],
|
||||
});
|
||||
mockListIDPLinks.mockResolvedValue({ result: [] });
|
||||
mockGetActiveIdentityProviders.mockResolvedValue({
|
||||
identityProviders: [{ id: "org-idp-123", type: 0 }],
|
||||
});
|
||||
mockIdpTypeToSlug.mockReturnValue("google");
|
||||
mockStartIdentityProviderFlow.mockResolvedValue("https://org-idp.example.com/auth");
|
||||
|
||||
const result = await sendLoginname({
|
||||
loginName: "[email protected]",
|
||||
});
|
||||
|
||||
expect(result).toEqual({ redirect: "https://org-idp.example.com/auth" });
|
||||
expect(mockGetActiveIdentityProviders).toHaveBeenCalledWith({
|
||||
serviceUrl: "https://api.example.com",
|
||||
orgId: "org123", // User's organization from resourceOwner
|
||||
});
|
||||
});
|
||||
|
||||
test("should redirect to passkey when user has only passkey method and it's allowed", async () => {
|
||||
mockGetLoginSettings.mockResolvedValue({ passkeysType: PasskeysType.ALLOWED });
|
||||
mockListAuthenticationMethodTypes.mockResolvedValue({
|
||||
@@ -373,6 +397,7 @@ describe("sendLoginname", () => {
|
||||
authMethodTypes: [AuthenticationMethodType.PASSWORD],
|
||||
});
|
||||
mockListIDPLinks.mockResolvedValue({ result: [] });
|
||||
mockGetActiveIdentityProviders.mockResolvedValue({ identityProviders: [] });
|
||||
|
||||
const result = await sendLoginname({
|
||||
loginName: "[email protected]",
|
||||
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
} from "../zitadel";
|
||||
import { createSessionAndUpdateCookie } from "./cookie";
|
||||
import { getOriginalHost } from "./host";
|
||||
import { IDPLink } from "@zitadel/proto/zitadel/user/v2/idp_pb";
|
||||
|
||||
export type SendLoginnameCommand = {
|
||||
loginName: string;
|
||||
@@ -68,63 +69,72 @@ export async function sendLoginname(command: SendLoginnameCommand) {
|
||||
|
||||
const { result: potentialUsers } = searchResult;
|
||||
|
||||
const redirectUserToSingleIDPIfAvailable = async () => {
|
||||
const identityProviders = await getActiveIdentityProviders({
|
||||
serviceUrl,
|
||||
orgId: command.organization,
|
||||
}).then((resp) => {
|
||||
return resp.identityProviders;
|
||||
});
|
||||
|
||||
if (identityProviders.length === 1) {
|
||||
const _headers = await headers();
|
||||
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
|
||||
const host = await getOriginalHost();
|
||||
|
||||
const identityProviderType = identityProviders[0].type;
|
||||
|
||||
const provider = idpTypeToSlug(identityProviderType);
|
||||
|
||||
const params = new URLSearchParams();
|
||||
|
||||
if (command.requestId) {
|
||||
params.set("requestId", command.requestId);
|
||||
}
|
||||
|
||||
if (command.organization) {
|
||||
params.set("organization", command.organization);
|
||||
}
|
||||
|
||||
const basePath = process.env.NEXT_PUBLIC_BASE_PATH ?? "";
|
||||
|
||||
const url = await startIdentityProviderFlow({
|
||||
const redirectUserToIDP = async (userId?: string, organization?: string) => {
|
||||
// If userId is provided, check for user-specific IDP links first
|
||||
let identityProviders: IDPLink[] = [];
|
||||
if (userId) {
|
||||
identityProviders = await listIDPLinks({
|
||||
serviceUrl,
|
||||
idpId: identityProviders[0].id,
|
||||
urls: {
|
||||
successUrl:
|
||||
`${host.includes("localhost") ? "http://" : "https://"}${host}${basePath}/idp/${provider}/success?` +
|
||||
new URLSearchParams(params),
|
||||
failureUrl:
|
||||
`${host.includes("localhost") ? "http://" : "https://"}${host}${basePath}/idp/${provider}/failure?` +
|
||||
new URLSearchParams(params),
|
||||
},
|
||||
userId,
|
||||
}).then((resp) => {
|
||||
return resp.result;
|
||||
});
|
||||
}
|
||||
|
||||
// If no IDP links exist for the user (or no userId provided), try to get active IDPs from the organization
|
||||
if (identityProviders.length === 0) {
|
||||
const activeIdps = await getActiveIdentityProviders({
|
||||
serviceUrl,
|
||||
orgId: organization,
|
||||
}).then((resp) => {
|
||||
return resp.identityProviders;
|
||||
});
|
||||
|
||||
if (!url) {
|
||||
return { error: t("errors.couldNotStartIDPFlow") };
|
||||
// If exactly one active IDP exists in the organization, redirect to it
|
||||
if (activeIdps.length === 1) {
|
||||
const _headers = await headers();
|
||||
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
|
||||
const host = await getOriginalHost();
|
||||
|
||||
const identityProviderType = activeIdps[0].type;
|
||||
const provider = idpTypeToSlug(identityProviderType);
|
||||
|
||||
const params = new URLSearchParams();
|
||||
|
||||
if (userId) {
|
||||
params.set("userId", userId);
|
||||
}
|
||||
|
||||
if (command.requestId) {
|
||||
params.set("requestId", command.requestId);
|
||||
}
|
||||
|
||||
if (organization) {
|
||||
params.set("organization", organization);
|
||||
}
|
||||
|
||||
const basePath = process.env.NEXT_PUBLIC_BASE_PATH ?? "";
|
||||
|
||||
const url = await startIdentityProviderFlow({
|
||||
serviceUrl,
|
||||
idpId: activeIdps[0].id,
|
||||
urls: {
|
||||
successUrl:
|
||||
`${host.includes("localhost") ? "http://" : "https://"}${host}${basePath}/idp/${provider}/success?` +
|
||||
new URLSearchParams(params),
|
||||
failureUrl:
|
||||
`${host.includes("localhost") ? "http://" : "https://"}${host}${basePath}/idp/${provider}/failure?` +
|
||||
new URLSearchParams(params),
|
||||
},
|
||||
});
|
||||
|
||||
if (!url) {
|
||||
return { error: t("errors.couldNotStartIDPFlow") };
|
||||
}
|
||||
|
||||
return { redirect: url };
|
||||
}
|
||||
|
||||
return { redirect: url };
|
||||
}
|
||||
};
|
||||
|
||||
const redirectUserToIDP = async (userId: string) => {
|
||||
const identityProviders = await listIDPLinks({
|
||||
serviceUrl,
|
||||
userId,
|
||||
}).then((resp) => {
|
||||
return resp.result;
|
||||
});
|
||||
|
||||
if (identityProviders.length === 1) {
|
||||
const _headers = await headers();
|
||||
@@ -147,14 +157,18 @@ export async function sendLoginname(command: SendLoginnameCommand) {
|
||||
const identityProviderType = idpTypeToIdentityProviderType(idpType);
|
||||
const provider = idpTypeToSlug(identityProviderType);
|
||||
|
||||
const params = new URLSearchParams({ userId });
|
||||
const params = new URLSearchParams();
|
||||
|
||||
if (userId) {
|
||||
params.set("userId", userId);
|
||||
}
|
||||
|
||||
if (command.requestId) {
|
||||
params.set("requestId", command.requestId);
|
||||
}
|
||||
|
||||
if (command.organization) {
|
||||
params.set("organization", command.organization);
|
||||
if (organization) {
|
||||
params.set("organization", organization);
|
||||
}
|
||||
|
||||
const basePath = process.env.NEXT_PUBLIC_BASE_PATH ?? "";
|
||||
@@ -240,6 +254,9 @@ export async function sendLoginname(command: SendLoginnameCommand) {
|
||||
return { error: t("errors.initialUserNotSupported") };
|
||||
}
|
||||
|
||||
// Resolve organization from command or session
|
||||
const organization = command.organization ?? session.factors?.user?.organizationId;
|
||||
|
||||
const methods = await listAuthenticationMethodTypes({
|
||||
serviceUrl,
|
||||
userId: session.factors?.user?.id,
|
||||
@@ -250,15 +267,15 @@ export async function sendLoginname(command: SendLoginnameCommand) {
|
||||
const params = new URLSearchParams({
|
||||
loginName: session.factors?.user?.loginName as string,
|
||||
send: "true", // set this to true to request a new code immediately
|
||||
invite: "true",
|
||||
invite: "true", // humanUser?.email?.isVerified ? "false" : "true", // sendInviteEmailCode results in an error if user is already initialized
|
||||
});
|
||||
|
||||
if (command.requestId) {
|
||||
params.append("requestId", command.requestId);
|
||||
}
|
||||
|
||||
if (command.organization || session.factors?.user?.organizationId) {
|
||||
params.append("organization", command.organization ?? (session.factors?.user?.organizationId as string));
|
||||
if (organization) {
|
||||
params.append("organization", organization);
|
||||
}
|
||||
|
||||
return { redirect: `/verify?` + params };
|
||||
@@ -270,7 +287,7 @@ export async function sendLoginname(command: SendLoginnameCommand) {
|
||||
case AuthenticationMethodType.PASSWORD: // user has only password as auth method
|
||||
if (!userLoginSettings?.allowUsernamePassword) {
|
||||
// Check if user has IDPs available as alternative, that could eventually be used to register/link.
|
||||
const idpResp = await redirectUserToIDP(userId);
|
||||
const idpResp = await redirectUserToIDP(userId, organization);
|
||||
if (idpResp?.redirect) {
|
||||
return idpResp;
|
||||
}
|
||||
@@ -286,8 +303,8 @@ export async function sendLoginname(command: SendLoginnameCommand) {
|
||||
|
||||
// TODO: does this have to be checked in loginSettings.allowDomainDiscovery
|
||||
|
||||
if (command.organization || session.factors?.user?.organizationId) {
|
||||
paramsPassword.append("organization", command.organization ?? session.factors?.user?.organizationId);
|
||||
if (organization) {
|
||||
paramsPassword.append("organization", organization);
|
||||
}
|
||||
|
||||
if (command.requestId) {
|
||||
@@ -312,14 +329,14 @@ export async function sendLoginname(command: SendLoginnameCommand) {
|
||||
paramsPasskey.append("requestId", command.requestId);
|
||||
}
|
||||
|
||||
if (command.organization || session.factors?.user?.organizationId) {
|
||||
paramsPasskey.append("organization", command.organization ?? session.factors?.user?.organizationId);
|
||||
if (organization) {
|
||||
paramsPasskey.append("organization", organization);
|
||||
}
|
||||
|
||||
return { redirect: "/passkey?" + paramsPasskey };
|
||||
|
||||
case AuthenticationMethodType.IDP:
|
||||
const resp = await redirectUserToIDP(userId);
|
||||
const resp = await redirectUserToIDP(userId, organization);
|
||||
|
||||
if (resp?.error) {
|
||||
return { error: resp.error };
|
||||
@@ -339,13 +356,13 @@ export async function sendLoginname(command: SendLoginnameCommand) {
|
||||
passkeyParams.append("requestId", command.requestId);
|
||||
}
|
||||
|
||||
if (command.organization || session.factors?.user?.organizationId) {
|
||||
passkeyParams.append("organization", command.organization ?? session.factors?.user?.organizationId);
|
||||
if (organization) {
|
||||
passkeyParams.append("organization", organization);
|
||||
}
|
||||
|
||||
return { redirect: "/passkey?" + passkeyParams };
|
||||
} else if (methods.authMethodTypes.includes(AuthenticationMethodType.IDP)) {
|
||||
return redirectUserToIDP(userId);
|
||||
return redirectUserToIDP(userId, organization);
|
||||
} else if (methods.authMethodTypes.includes(AuthenticationMethodType.PASSWORD)) {
|
||||
// Check if password authentication is allowed
|
||||
if (!userLoginSettings?.allowUsernamePassword) {
|
||||
@@ -363,8 +380,8 @@ export async function sendLoginname(command: SendLoginnameCommand) {
|
||||
paramsPasswordDefault.append("requestId", command.requestId);
|
||||
}
|
||||
|
||||
if (command.organization || session.factors?.user?.organizationId) {
|
||||
paramsPasswordDefault.append("organization", command.organization ?? session.factors?.user?.organizationId);
|
||||
if (organization) {
|
||||
paramsPasswordDefault.append("organization", organization);
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -376,7 +393,7 @@ export async function sendLoginname(command: SendLoginnameCommand) {
|
||||
|
||||
// user not found, check if register is enabled on instance / organization context
|
||||
if (loginSettingsByContext?.allowRegister && !loginSettingsByContext?.allowUsernamePassword) {
|
||||
const resp = await redirectUserToSingleIDPIfAvailable();
|
||||
const resp = await redirectUserToIDP(undefined, command.organization);
|
||||
if (resp) {
|
||||
return resp;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user