지영이의 개발 블로그

next-auth 로 사용자 인증 구현 (구글 , 카카오 , 네이버) 본문

next js

next-auth 로 사용자 인증 구현 (구글 , 카카오 , 네이버)

이지영 2024. 1. 31. 18:50

1. 먼저, 프로젝트에 next-auth를 설치해야 합니다. 터미널에서 다음 명령어를 실행하여 설치하세요:

yarn add next-auth

 

2.Next.js 프로젝트의 pages/api/auth/[...nextauth].js 파일을 생성하고 다음 코드를 추가하세요:

import NextAuth from "next-auth"
import GithubProvider from "next-auth/providers/github"
export const authOptions = {
  // Configure one or more authentication providers
  providers: [
    GithubProvider({
      clientId: process.env.GITHUB_ID,
      clientSecret: process.env.GITHUB_SECRET,
    }),
    // ...add more providers here
  ],
}

 

3._app.js 파일에 session provider 설정

import { SessionProvider } from "next-auth/react"
export default function App({
  Component,
  pageProps: { session, ...pageProps },
}) {
  return (
    <SessionProvider session={session}>
      <Component {...pageProps} />
    </SessionProvider>
  )

4.usesession() 및 인증 훅으로 사용자 관리 (로그인 유무 등 )

import { useSession, signIn, signOut } from "next-auth/react"
export default function Component() {
  const { data: session } = useSession()
  if (session) {
    return (
      <>
        Signed in as {session.user.email} <br />
        <button onClick={() => signOut()}>Sign out</button>
      </>
    )
  }
  return (
    <>
      Not signed in <br />
      <button onClick={() => signIn()}>Sign in</button>
    </>
  )
}

prisma adapter 세팅

1. 설치

yarn add @auth/prisma-adapter

 

2. next - auth 파일에 정의

import NextAuth from "next-auth"
import Providers from "next-auth/providers"
import { PrismaAdapter } from "@next-auth/prisma-adapter"
import { PrismaClient } from "@prisma/client"

const prisma = new PrismaClient()

export default NextAuth({
  providers: [
    Providers.Google({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    }),
  ],
  adapter: PrismaAdapter(prisma),
})

 

3. prisma/schema.prisma다음과 유사한 스키마 파일을 만듭니다 .

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "sqlite"
  url      = "file:./dev.db"
}

model Account {
  id                 String    @id @default(cuid())
  userId             String
  providerType       String
  providerId         String
  providerAccountId  String
  refreshToken       String?
  accessToken        String?
  accessTokenExpires DateTime?
  createdAt          DateTime  @default(now())
  updatedAt          DateTime  @updatedAt
  user               User      @relation(fields: [userId], references: [id])

  @@unique([providerId, providerAccountId])
}

model Session {
  id           String   @id @default(cuid())
  userId       String
  expires      DateTime
  sessionToken String   @unique
  accessToken  String   @unique
  createdAt    DateTime @default(now())
  updatedAt    DateTime @updatedAt
  user         User     @relation(fields: [userId], references: [id])
}

model User {
  id            String    @id @default(cuid())
  name          String?
  email         String?   @unique
  emailVerified DateTime?
  image         String?
  createdAt     DateTime  @default(now())
  updatedAt     DateTime  @updatedAt
  accounts      Account[]
  sessions      Session[]
}

model VerificationRequest {
  id         String   @id @default(cuid())
  identifier String
  token      String   @unique
  expires    DateTime
  createdAt  DateTime @default(now())
  updatedAt  DateTime @updatedAt

  @@unique([identifier, token])
}

middleware 세팅

특정경로에서 항상 로그인을 해야하는 경우 , middleware통해 보안을 걸 수 있음

경로 (src/middleware.ts)

export { default } from "next-auth/middleware"

export const config = { matcher: ["/dashboard"] }

* .env 파일에 NEXTAUTH_SECRET 생성후 , 로그인이 필요한 페이지 경로를 Middleware 를 통해 정의 

 

 

 

 

- 참고  : https://next-auth.js.org/getting-started/example

 

Getting Started | NextAuth.js

The example code below describes how to add authentication to a Next.js app.

next-auth.js.org

- 참고 : https://next-auth.js.org/v3/adapters/prisma

 

Prisma Adapter | NextAuth.js

You can also use NextAuth.js with the new experimental Adapter for Prisma. This version of the Prisma Adapter is not included in the core next-auth package, and must be installed separately.

next-auth.js.org

- 참고 : https://next-auth.js.org/configuration/nextjs#middleware

 

Next.js | NextAuth.js

getServerSession

next-auth.js.org

 

Comments