Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions app/auth/dg/login/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { createHash, randomBytes } from "node:crypto";
import { NextResponse } from "next/server";

const DATAGSM_AUTHORIZE_URL = "https://oauth.authorization.datagsm.kr/v1/oauth/authorize";
const OAUTH_CALLBACK_PATH = "/oauth/callback";
const OAUTH_COOKIE_MAX_AGE_SECONDS = 60 * 5;

function createPkceCodeVerifier() {
return randomBytes(64).toString("base64url");
}

function createPkceCodeChallenge(codeVerifier: string) {
return createHash("sha256").update(codeVerifier).digest("base64url");
}

function createState() {
return randomBytes(32).toString("base64url");
}

export async function GET(request: Request) {
const clientId = process.env.NEXT_PUBLIC_DATAGSM_CLIENT_ID;

if (!clientId) {
return NextResponse.json(
{ message: "NEXT_PUBLIC_DATAGSM_CLIENT_ID is not configured." },
{ status: 500 },
);
}

const requestUrl = new URL(request.url);
const redirectUri = new URL(OAUTH_CALLBACK_PATH, requestUrl.origin).toString();
Comment on lines +30 to +31

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

🚨 프록시 환경에서 잘못된 Redirect URI 생성 위험

현재 request.url에서 직접 origin을 추출하여 redirectUri를 생성하고 있습니다.

Next.js 애플리케이션이 Vercel, Docker, Nginx 등의 리버스 프록시 뒤에서 실행되는 경우, request.url은 실제 클라이언트가 접속한 도메인이 아닌 내부 주소(예: http://localhost:3000 또는 내부 IP)를 가질 수 있습니다. 이로 인해 OAuth 인증 서버로 잘못된 redirect_uri가 전달되어 로그인 흐름이 완전히 깨질 수 있습니다.

이를 방지하기 위해 x-forwarded-hostx-forwarded-proto 헤더를 참조하여 동적으로 올바른 외부 Origin을 구성하는 것이 안전합니다.

Suggested change
const requestUrl = new URL(request.url);
const redirectUri = new URL(OAUTH_CALLBACK_PATH, requestUrl.origin).toString();
const requestUrl = new URL(request.url);
const host = request.headers.get("x-forwarded-host") || requestUrl.host;
const proto = request.headers.get("x-forwarded-proto") || (requestUrl.protocol === "https:" ? "https" : "http");
const origin = `${proto}://${host}`;
const redirectUri = new URL(OAUTH_CALLBACK_PATH, origin).toString();

const state = createState();
const codeVerifier = createPkceCodeVerifier();
const codeChallenge = createPkceCodeChallenge(codeVerifier);

const authorizeUrl = new URL(DATAGSM_AUTHORIZE_URL);
authorizeUrl.searchParams.set("client_id", clientId);
authorizeUrl.searchParams.set("redirect_uri", redirectUri);
authorizeUrl.searchParams.set("response_type", "code");
authorizeUrl.searchParams.set("state", state);
authorizeUrl.searchParams.set("code_challenge", codeChallenge);
authorizeUrl.searchParams.set("code_challenge_method", "S256");

const response = NextResponse.redirect(authorizeUrl);

response.cookies.set("dg_oauth_state", state, {
httpOnly: true,
maxAge: OAUTH_COOKIE_MAX_AGE_SECONDS,
path: "/auth/dg",
sameSite: "lax",
});
response.cookies.set("dg_oauth_code_verifier", codeVerifier, {
httpOnly: true,
maxAge: OAUTH_COOKIE_MAX_AGE_SECONDS,
path: "/auth/dg",
sameSite: "lax",
});
response.cookies.set("dg_oauth_redirect_uri", redirectUri, {
httpOnly: true,
maxAge: OAUTH_COOKIE_MAX_AGE_SECONDS,
path: "/auth/dg",
sameSite: "lax",
});
Comment on lines +46 to +63

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security-medium medium

🔒 OAuth 보안 쿠키에 secure 옵션 누락

OAuth state, code_verifier, redirect_uri는 세션 고정(Session Fixation) 및 CSRF 공격을 방지하기 위한 민감한 보안 데이터입니다.

운영(production) 환경에서는 이 쿠키들이 반드시 HTTPS 연결을 통해서만 전송되도록 secure: process.env.NODE_ENV === "production" 옵션을 추가하는 것이 안전합니다.

  response.cookies.set("dg_oauth_state", state, {
    httpOnly: true,
    secure: process.env.NODE_ENV === "production",
    maxAge: OAUTH_COOKIE_MAX_AGE_SECONDS,
    path: "/auth/dg",
    sameSite: "lax",
  });
  response.cookies.set("dg_oauth_code_verifier", codeVerifier, {
    httpOnly: true,
    secure: process.env.NODE_ENV === "production",
    maxAge: OAUTH_COOKIE_MAX_AGE_SECONDS,
    path: "/auth/dg",
    sameSite: "lax",
  });
  response.cookies.set("dg_oauth_redirect_uri", redirectUri, {
    httpOnly: true,
    secure: process.env.NODE_ENV === "production",
    maxAge: OAUTH_COOKIE_MAX_AGE_SECONDS,
    path: "/auth/dg",
    sameSite: "lax",
  });


return response;
}
2 changes: 1 addition & 1 deletion app/globals.css
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@

--font-family-base:
"Pretendard Variable", Pretendard, -apple-system, BlinkMacSystemFont, system-ui, sans-serif;
--font-logo: "Black Han Sans", sans-serif;
--font-logo: var(--font-black-han-sans), sans-serif;

--radius-sm: 4px;
--radius-md: 8px;
Expand Down
15 changes: 8 additions & 7 deletions app/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,27 @@
import type { Metadata } from "next";
import { Black_Han_Sans } from "next/font/google";
import { QueryProvider } from "@/shared/providers/query-provider";
import "./globals.css";

const blackHanSans = Black_Han_Sans({
subsets: ["latin"],
weight: "400",
variable: "--font-black-han-sans",
});

export const metadata: Metadata = {
title: "취준",
description: "한국 취준생을 위한 코딩 테스트 풀이 플랫폼",
};

export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="ko">
<html lang="ko" className={blackHanSans.variable}>
<head>
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/gh/orioncactus/pretendard@v1.3.9/dist/web/variable/pretendardvariable.min.css"
/>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossOrigin="anonymous" />
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css2?family=Black+Han+Sans&display=swap"
/>
</head>
<body>
<QueryProvider>{children}</QueryProvider>
Expand Down
9 changes: 1 addition & 8 deletions middleware.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { NextResponse, type NextRequest } from "next/server";
import { PUBLIC_ROUTES, REFRESH_TOKEN_COOKIE } from "@/shared/config/routes";
import { REFRESH_TOKEN_COOKIE } from "@/shared/config/routes";

export const config = {
matcher: ["/((?!api|auth|_next/static|_next/image|favicon.ico|.*\\..*).*)"],
Expand All @@ -13,12 +13,5 @@ export function middleware(request: NextRequest) {
if (pathname === "/signin" && refreshToken) {
return NextResponse.redirect(new URL("/", request.url));
}

// 비공개 경로 + 미인증 → /signin 으로.
const isPublic = PUBLIC_ROUTES.some((route) => route === pathname);
// if (!isPublic && !refreshToken) {
// return NextResponse.redirect(new URL("/signin", request.url));
// }

return NextResponse.next();
}
4 changes: 2 additions & 2 deletions src/shared/ui/dg-signin-button.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import { DGIcon } from "@/shared/assets/DGIcon";

export function DgSigninButton() {
const handleLogin = () => {
// 백엔드(/auth/dg/login)가 PKCE 쿠키를 심고 DataGSM 으로 리다이렉트해야 하므로
// SPA 라우팅이 아니라 same-origin 프록시를 타는 전체 페이지 이동이어야 한다.
// same-origin Route Handler 가 현재 origin 기준 PKCE 쿠키를 심고
// DataGSM 인증 페이지로 넘겨야 하므로 전체 페이지 이동으로 시작한다.
window.location.href = "/auth/dg/login";
};

Expand Down
Loading