fix oidc callback behind reverse proxy
This commit is contained in:
44
proxy.ts
44
proxy.ts
@@ -1,6 +1,12 @@
|
||||
import { getToken } from "next-auth/jwt";
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { getAuthMode, getRequiredAuthSecret, isAuthRoute, isProtectedPath } from "@/lib/auth-config";
|
||||
import {
|
||||
getAuthMode,
|
||||
getRequiredAuthSecret,
|
||||
isAuthRoute,
|
||||
isProtectedPath,
|
||||
type AuthEnv,
|
||||
} from "@/lib/auth-config";
|
||||
|
||||
export async function proxy(request: NextRequest) {
|
||||
const { pathname } = request.nextUrl;
|
||||
@@ -24,8 +30,9 @@ export async function proxy(request: NextRequest) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
const signInUrl = new URL("/api/auth/signin/oidc", request.url);
|
||||
signInUrl.searchParams.set("callbackUrl", request.nextUrl.href);
|
||||
const callbackUrl = buildPublicRequestUrl(request);
|
||||
const signInUrl = new URL("/api/auth/signin/oidc", callbackUrl);
|
||||
signInUrl.searchParams.set("callbackUrl", callbackUrl.href);
|
||||
return NextResponse.redirect(signInUrl);
|
||||
}
|
||||
|
||||
@@ -46,6 +53,37 @@ function authConfigErrorResponse(request: NextRequest, error: string) {
|
||||
});
|
||||
}
|
||||
|
||||
export function buildPublicRequestUrl(request: NextRequest, env: AuthEnv = process.env): URL {
|
||||
const origin = getPublicOrigin(request, env);
|
||||
return new URL(`${request.nextUrl.pathname}${request.nextUrl.search}`, origin);
|
||||
}
|
||||
|
||||
function getPublicOrigin(request: NextRequest, env: AuthEnv): string {
|
||||
const configuredOrigin = getConfiguredOrigin(env.NEXTAUTH_URL);
|
||||
if (configuredOrigin) return configuredOrigin;
|
||||
|
||||
const forwardedHost = firstHeaderValue(request.headers.get("x-forwarded-host"));
|
||||
const host = forwardedHost || firstHeaderValue(request.headers.get("host")) || request.nextUrl.host;
|
||||
const forwardedProto = firstHeaderValue(request.headers.get("x-forwarded-proto"));
|
||||
const proto = forwardedProto || request.nextUrl.protocol.replace(":", "") || "http";
|
||||
|
||||
return `${proto}://${host}`;
|
||||
}
|
||||
|
||||
function getConfiguredOrigin(value: string | undefined): string | null {
|
||||
if (!value?.trim()) return null;
|
||||
|
||||
try {
|
||||
return new URL(value).origin;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function firstHeaderValue(value: string | null): string {
|
||||
return value?.split(",")[0]?.trim() ?? "";
|
||||
}
|
||||
|
||||
function authErrorHtml(error: string): string {
|
||||
return `<!doctype html>
|
||||
<html lang="zh">
|
||||
|
||||
Reference in New Issue
Block a user