반응형
아직도 next auth를 쓰는 이유는 모르지만 보안적으로 더 좋아졋다 라고 하니 사용을 해보겠다.
01. middleware
//middleware.ts
import { auth } from './auth'
import { NextResponse } from 'next/server'
export async function middleware() {
const session = await auth()
// 아래 페이지 중 로그인이 안됫을시
if (!session) {
return NextResponse.redirect('http://localhost:3000/login')
}
}
// See "Matching Paths" below to learn more
export const config = {
matcher: ['/sell', '/room']
}
여기서 config는 로그인이 됫는지 안됫는지를 확인하고 로그인이 안됫다 라고 하면 위의 로그인 페이지로 넘겨 버린다.
결국 이 미들웨어는 이페이지를 들어가려면 로그인을 해야하는데 햇어? 이소리다.
02 auth
import NextAuth from 'next-auth'
import CredentialsProvider from 'next-auth/providers/credentials'
import { cookies } from 'next/headers'
import cookie from 'cookie'
interface MyCredentialsConfig {
credentials: Record<string, string>
authorize(credentials: Record<string, string>): Promise<any>
}
export const {
handlers: { GET, POST },
auth,
signIn
} = NextAuth({
pages: {
signIn: '/login',
newUser: '/signup'
},
providers: [
CredentialsProvider({
credentials: {
// Existing logic for username and password
},
async authorize(credentials) {
const authResponse = await fetch(
`${process.env.NEXT_PUBLIC_BASE_URL}/user/login`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
id: (credentials as { username: string }).username,
password: (credentials as { password: string }).password
})
}
)
let setCookie = authResponse.headers.get('Set-Cookie')
console.log('set-cookie', setCookie)
if (setCookie) {
const parsed = cookie.parse(setCookie)
cookies().set('connect.sid', parsed['connect.sid'], parsed) // 브라우저에 쿠키를 심어주는 것
}
if (!authResponse.ok) {
return null
}
const user = await authResponse.json()
console.log('user', user)
return {
name: user.nickname,
image: user.image,
...user
}
}
})
]
})
클라이언트 사이드에서 인증 상태를 관리할수 있게 하는 초석이라 보면 된다. 위 코드는 크게 아래 부분으로 나누어 볼 수 있다:
- 로그인과 회원가입을 처리하는 페이지 루트를 추가한다.
- API의 /user/login 엔드포인트로 이메일과 비밀번호를 POST한다.
- 백엔드에서 connect.sid로 시작하는 쿠키를 보내줄건데, 이를 돌아온 응답의 Set-Cookie 헤더에서 가져오고, 설정한다.
- 현재 사용중인 next-auth의 버전인 5.0.0-beta.13에 버그가 있는데, response.ok 값이 로그인에 실패해도 true로 떠서 authResponse.status === 401을 추가하여 핸들링하고 있다.
- 최종적으로 id와 name에 유저 이메일과 nickname을 할당한다. DefaultUser를 상속받고 있어서 id 인자와 name 인자가 필수적으로 들어가야 하는데, 여기에 내가 원하는 속성으로 바꿀 수 있다.
03. AuthSession.tsx
//AuthSession.tsx
'use client';
import { SessionProvider } from "next-auth/react";
type Props = ({
children: React.ReactNode;
});
export default function AuthSession({ children }: Props) {
return <SessionProvider>{children}</SessionProvider>;
}
이거는 클라이언트 컴포넌츠 측에서 인증세션 상태 접근을 위한 거
반응형