mirror of
https://github.com/andwati/zitadel.git
synced 2026-11-27 14:48:45 +00:00
chore(login): Extract auth flow utilities and eliminate RSC request interference (#10644)
The /login route was experiencing issues with React Server Component
(RSC) requests interfering with one-time authentication callbacks. When
users navigated to /login via client-side routing (router.push()),
Next.js automatically triggered _rsc requests that could consume
single-use createCallback tokens, breaking OIDC and SAML authentication
flows.
# Which Problems Are Solved
When users attempt to log in, Next.js automatically makes requests with
the `_rsc=1` query parameter for React Server Components. The current
implementation treats these as server errors:
```typescript
// Before
if (_rsc) {
return NextResponse.json({ error: "No _rsc supported" }, { status: 500 });
}
```
This results in:
- Spurious 500 error logs polluting monitoring systems
- False alerts for server failures
- Difficulty distinguishing real issues from benign RSC requests
# How the Problems Are Solved
This PR implements a comprehensive refactoring that:
- Eliminates RSC interference by providing server actions for internal
auth flow completion
- Separates concerns between external flow initiation and internal flow
completion
- Extracts shared utilities to improve code maintainability and
reusability
- Maintains full backward compatibility for external applications
# Additional Context
## New Architecture
- auth-flow.ts: Shared utilities for auth flow completion with RSC
protection
- flow-initiation.ts: Extracted OIDC/SAML flow initiation logic (~400
lines)
- auth.ts: Server actions for internal components
## Route Handler Simplification
- route.ts: Reduced from ~350 lines to ~75 lines
- External-only focus: Now handles only flow initiation for external
applications
- Removed completion logic: External apps use their own callback URLs
- Enhanced validation: Early RSC blocking and parameter validation
## Flow Logic Improvements
- Early return patterns: Guard clauses eliminate deep nesting
- Better error handling: Specific error messages for different failure
modes
- Fixed SAML flow: Addressed incomplete logic
- Consistent session handling: Unified approach across OIDC and SAML
This commit is contained in:
@@ -3,22 +3,20 @@
|
||||
import {
|
||||
getLoginSettings,
|
||||
getUserByID,
|
||||
listAuthenticationMethodTypes,
|
||||
startIdentityProviderFlow,
|
||||
startLDAPIdentityProviderFlow,
|
||||
} from "@/lib/zitadel";
|
||||
import { headers } from "next/headers";
|
||||
import { redirect } from "next/navigation";
|
||||
import { getNextUrl } from "../client";
|
||||
import { completeFlowOrGetUrl } from "../client";
|
||||
import { getServiceUrlFromHeaders } from "../service-url";
|
||||
import { checkEmailVerification } from "../verify-helper";
|
||||
import { checkEmailVerification, checkMFAFactors } from "../verify-helper";
|
||||
import { createSessionForIdpAndUpdateCookie } from "./cookie";
|
||||
|
||||
export type RedirectToIdpState = { error?: string | null } | undefined;
|
||||
|
||||
export async function redirectToIdp(
|
||||
prevState: RedirectToIdpState,
|
||||
formData: FormData,
|
||||
): Promise<RedirectToIdpState> {
|
||||
export async function redirectToIdp(prevState: RedirectToIdpState, formData: FormData): Promise<RedirectToIdpState> {
|
||||
const _headers = await headers();
|
||||
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
|
||||
const host = _headers.get("host");
|
||||
@@ -102,9 +100,7 @@ type CreateNewSessionCommand = {
|
||||
requestId?: string;
|
||||
};
|
||||
|
||||
export async function createNewSessionFromIdpIntent(
|
||||
command: CreateNewSessionCommand,
|
||||
) {
|
||||
export async function createNewSessionFromIdpIntent(command: CreateNewSessionCommand) {
|
||||
const _headers = await headers();
|
||||
|
||||
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
|
||||
@@ -143,30 +139,43 @@ export async function createNewSessionFromIdpIntent(
|
||||
return { error: "Could not create session" };
|
||||
}
|
||||
|
||||
const humanUser =
|
||||
userResponse.user.type.case === "human"
|
||||
? userResponse.user.type.value
|
||||
: undefined;
|
||||
const humanUser = userResponse.user.type.case === "human" ? userResponse.user.type.value : undefined;
|
||||
|
||||
// check to see if user was verified
|
||||
const emailVerificationCheck = checkEmailVerification(
|
||||
session,
|
||||
humanUser,
|
||||
command.organization,
|
||||
command.requestId,
|
||||
);
|
||||
const emailVerificationCheck = checkEmailVerification(session, humanUser, command.organization, command.requestId);
|
||||
|
||||
if (emailVerificationCheck?.redirect) {
|
||||
return emailVerificationCheck;
|
||||
}
|
||||
|
||||
// TODO: check if user has MFA methods
|
||||
// const mfaFactorCheck = checkMFAFactors(session, loginSettings, authMethods, organization, requestId);
|
||||
// if (mfaFactorCheck?.redirect) {
|
||||
// return mfaFactorCheck;
|
||||
// }
|
||||
// check if user has MFA methods
|
||||
let authMethods;
|
||||
if (session.factors?.user?.id) {
|
||||
const response = await listAuthenticationMethodTypes({
|
||||
serviceUrl,
|
||||
userId: session.factors.user.id,
|
||||
});
|
||||
if (response.authMethodTypes && response.authMethodTypes.length) {
|
||||
authMethods = response.authMethodTypes;
|
||||
}
|
||||
}
|
||||
|
||||
const url = await getNextUrl(
|
||||
if (authMethods) {
|
||||
const mfaFactorCheck = await checkMFAFactors(
|
||||
serviceUrl,
|
||||
session,
|
||||
loginSettings,
|
||||
authMethods,
|
||||
command.organization,
|
||||
command.requestId,
|
||||
);
|
||||
|
||||
if (mfaFactorCheck?.redirect) {
|
||||
return mfaFactorCheck;
|
||||
}
|
||||
}
|
||||
|
||||
return completeFlowOrGetUrl(
|
||||
command.requestId && session.id
|
||||
? {
|
||||
sessionId: session.id,
|
||||
@@ -179,10 +188,6 @@ export async function createNewSessionFromIdpIntent(
|
||||
},
|
||||
loginSettings?.defaultRedirectUri,
|
||||
);
|
||||
|
||||
if (url) {
|
||||
return { redirect: url };
|
||||
}
|
||||
}
|
||||
|
||||
type createNewSessionForLDAPCommand = {
|
||||
@@ -192,9 +197,7 @@ type createNewSessionForLDAPCommand = {
|
||||
link: boolean;
|
||||
};
|
||||
|
||||
export async function createNewSessionForLDAP(
|
||||
command: createNewSessionForLDAPCommand,
|
||||
) {
|
||||
export async function createNewSessionForLDAP(command: createNewSessionForLDAPCommand) {
|
||||
const _headers = await headers();
|
||||
|
||||
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
|
||||
@@ -215,11 +218,7 @@ export async function createNewSessionForLDAP(
|
||||
password: command.password,
|
||||
});
|
||||
|
||||
if (
|
||||
!response ||
|
||||
response.nextStep.case !== "idpIntent" ||
|
||||
!response.nextStep.value
|
||||
) {
|
||||
if (!response || response.nextStep.case !== "idpIntent" || !response.nextStep.value) {
|
||||
return { error: "Could not start LDAP identity provider flow" };
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user