Next.js 앱 라우터에서 Auth.js를 사용한 사용자 인증
목차
초기 설정
- 설치
-
구성
- NextAuthConfig 설정
- 경로 처리기 설정
- 미들웨어
- 서버측 구성요소에서 세션 가져오기
- 클라이언트 측 구성 요소에서 세션 가져오기
- 폴더 구조
인증 구현: 자격 증명 및 Google OAuth
- 프리즈마 설정
- 자격증명
-
Google OAuth 제공업체 추가
- Google OAuth 애플리케이션 설정
- 리디렉션 URI 설정
- 환경변수 설정
- 설정 제공업체
- 로그인 및 회원가입 페이지 만들기
- 폴더 구조
초기 설정
설치하다
npm install next-auth@beta
// env.local AUTH_SECRET=GENERATETD_RANDOM_VALUE
구성
NextAuthConfig 설정
// src/auth.ts import NextAuth from "next-auth" export const config = { providers: [], } export const { handlers, signIn, signOut, auth } = NextAuth(config)
src 폴더
에 넣어야 합니다.
공급자는 Auth.js에서 사용자 로그인에 사용할 수 있는 서비스를 의미합니다. 사용자가 로그인할 수 있는 방법은 4가지가 있습니다.
- 내장 OAuth 제공자(예: Github, Google 등...) 사용
- 맞춤형 OAuth 공급자 사용
- 이메일 사용
- 자격증명 사용
https://authjs.dev/reference/nextjs#providers
경로 처리기 설정
// src/app/api/auth/[...nextauth]/route.ts import { handlers } from "@/auth" // Referring to the auth.ts we just created export const { GET, POST } = handlers
이 파일은 Next.js App Router를 사용하여 경로 핸들러를 설정하는 데 사용됩니다.
미들웨어
// src/middleware.ts import { auth } from "@/auth" export default auth((req) => { // Add your logic here } export const config = { matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"], // It's default setting }
src 폴더 안에 작성하세요.
src 폴더 외부에 작성하면 미들웨어가 작동하지 않습니다.
미들웨어는 요청이 완료되기 전에 코드를 실행할 수 있게 해주는 기능입니다. 이는 애플리케이션 전체에서 경로를 보호하고 인증을 처리하는 데 특히 유용합니다.
Matcher는 미들웨어가 적용되어야 하는 경로를 지정하는 구성 옵션입니다. 필요한 경로에서만 미들웨어를 실행하여 성능을 최적화하는 데 도움이 됩니다.
예시 매처: ['/dashboard/:path*'] 대시보드 경로에만 미들웨어를 적용합니다.
https://authjs.dev/getting-started/session-management/protecting?framework=express#nextjs-middleware
서버 측 구성 요소에서 세션 가져오기
// src/app/page.tsx import { auth } from "@/auth" import { redirect } from "next/navigation" export default async function page() { const session = await auth() if (!session) { redirect('/login') } return ( <div> <h1>Hello World!</h1> <img src={session.user.image} alt="User Avatar" /> </div> ) }
클라이언트 측 구성 요소에서 세션 가져오기
// src/app/page.tsx "use client" import { useSession } from "next-auth/react" import { useRouter } from "next/navigation" export default async function page() { const { data: session } = useSession() const router = useRouter() if (!session.user) { router.push('/login') } return ( <div> <h1>Hello World!</h1> <img src={session.user.image} alt="User Avatar" /> </div> ) } // src/app/layout.tsx import type { Metadata } from "next"; import "./globals.css"; import { SessionProvider } from "next-auth/react" export const metadata: Metadata = { title: "Create Next App", description: "Generated by create next app", }; export default function RootLayout({ children, }: Readonly<{ children: React.ReactNode; }>) { return ( <html lang="en"> <body> <SessionProvider> {children} </SessionProvider> </body> </html> ); }
폴더 구조
/src /app /api /auth [...nextauth] /route.ts // Route Handler layout.tsx page.tsx auth.ts // Provider, Callback, Logic etc middleware.ts // A function before request
인증 구현: 자격 증명 및 Google OAuth
프리즈마 설정
// prisma/schema.prisma model User { id String @id @default(cuid()) name String? email String? @unique emailVerified DateTime? image String? password String? accounts Account[] sessions Session[] } model Account { // ... (standard Auth.js Account model) } model Session { // ... (standard Auth.js Session model) } // ... (other necessary models)
// src/lib/prisma.ts import { PrismaClient } from "@prisma/client" const globalForPrisma = globalThis as unknown as { prisma: PrismaClient } export const prisma = globalForPrisma.prisma || new PrismaClient() if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma
신임장
자격증명은 인증이라는 맥락에서 사용자가 제공하는 사용자의 신원을 확인하는 방법, 일반적으로 사용자 이름(또는 이메일)과 비밀번호를 의미합니다.
src/auth.ts에 자격 증명을 추가할 수 있습니다.
npm install next-auth@beta
어댑터:
- 인증 시스템을 데이터베이스 또는 데이터 스토리지 솔루션에 연결하는 모듈입니다.
비밀:
- 토큰 해시, 쿠키 서명/암호화, 암호화 키 생성에 사용되는 임의의 문자열입니다.
- 보안에 매우 중요하므로 비밀로 유지해야 합니다.
- 이 경우에는 AUTH_SECRET 환경 변수를 사용하여 설정됩니다.
페이지:
- 이 개체를 사용하면 인증 페이지의 URL을 사용자 정의할 수 있습니다.
- 귀하의 예에서 signIn: '/login'은 로그인 페이지가 기본 '/api/auth/signin' 대신 '/login' 경로에 있음을 의미합니다.
세션:
- 세션 처리 방법을 구성합니다.
- 전략: "jwt"는 데이터베이스 세션 대신 세션 관리에 JSON 웹 토큰이 사용된다는 의미입니다.
콜백:
- 인증 흐름의 다양한 지점에서 호출되는 함수로, 프로세스를 맞춤설정할 수 있습니다.
jwt 콜백:
- JWT가 생성되거나 업데이트될 때 실행됩니다.
- 귀하의 코드에서는 사용자 정보(ID, 이메일, 이름)를 토큰에 추가합니다.
세션 콜백:
- 세션을 확인할 때마다 실행됩니다.
- 귀하의 코드는 토큰의 사용자 정보를 세션 개체에 추가하고 있습니다.
Google OAuth 제공업체 추가
Google OAuth 애플리케이션 설정
GCP 콘솔에서 새 OAuth 클라이언트 ID 만들기 > API 및 서비스 > 자격 증명
생성한 후에는 나중에 사용할 수 있도록 클라이언트 ID와 클라이언트 비밀번호를 저장하세요.
리디렉션 URI 설정
로컬에서 작업할 때는 http://localhost:3000/api/auth/callback/google을 설정하세요
프로덕션 환경에서는 http://localhost:3000을 https://------로 바꾸면 됩니다.
환경 변수 설정
// env.local AUTH_SECRET=GENERATETD_RANDOM_VALUE
설치 공급자
// src/auth.ts import NextAuth from "next-auth" export const config = { providers: [], } export const { handlers, signIn, signOut, auth } = NextAuth(config)
https://authjs.dev/getting-started/authentication/oauth
로그인 및 회원가입 페이지 생성
// src/app/api/auth/[...nextauth]/route.ts import { handlers } from "@/auth" // Referring to the auth.ts we just created export const { GET, POST } = handlers
// src/middleware.ts import { auth } from "@/auth" export default auth((req) => { // Add your logic here } export const config = { matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"], // It's default setting }
// src/app/page.tsx import { auth } from "@/auth" import { redirect } from "next/navigation" export default async function page() { const session = await auth() if (!session) { redirect('/login') } return ( <div> <h1>Hello World!</h1> <img src={session.user.image} alt="User Avatar" /> </div> ) }
// src/app/page.tsx "use client" import { useSession } from "next-auth/react" import { useRouter } from "next/navigation" export default async function page() { const { data: session } = useSession() const router = useRouter() if (!session.user) { router.push('/login') } return ( <div> <h1>Hello World!</h1> <img src={session.user.image} alt="User Avatar" /> </div> ) } // src/app/layout.tsx import type { Metadata } from "next"; import "./globals.css"; import { SessionProvider } from "next-auth/react" export const metadata: Metadata = { title: "Create Next App", description: "Generated by create next app", }; export default function RootLayout({ children, }: Readonly<{ children: React.ReactNode; }>) { return ( <html lang="en"> <body> <SessionProvider> {children} </SessionProvider> </body> </html> ); }
/src /app /api /auth [...nextauth] /route.ts // Route Handler layout.tsx page.tsx auth.ts // Provider, Callback, Logic etc middleware.ts // A function before request
폴더 구조
// prisma/schema.prisma model User { id String @id @default(cuid()) name String? email String? @unique emailVerified DateTime? image String? password String? accounts Account[] sessions Session[] } model Account { // ... (standard Auth.js Account model) } model Session { // ... (standard Auth.js Session model) } // ... (other necessary models)
위 내용은 Next.js 앱 라우터에서 Auth.js를 사용한 사용자 인증의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제









