패스워드 암호화
1. 라이브러리 설치
npm install bcrypt
2. import 라이브러리
import bcrypt from "bcrypt";
3. 패스워드 암호화
const hash = await bcrypt.hash(req.body.pw, 10);
=> 회원가입 시 pw를 해쉬 작업
4. DB에 넣기
req.body.pw = hash;
await db.collection("user").insertOne(req.body);
5. DB 확인
=> DB관리자도 클라이언트의 pw를 확인할 수 없게 해쉬화 하는 용도
=> 클라이언트가 원래 pw로 로그인을 하면 정상적으로 로그인 가능.
Credentials provider 설정
1. import 라이브러리
import CredentialsProvider from "next-auth/providers/credentials";
import bcrypt from 'bcrypt';
2. 코드 작성
export const authOptions = {
providers: [
CredentialsProvider({
//1. 로그인페이지 폼 자동생성
name: "credentials",
credentials: {
email: { label: "email", type: "text" },
password: { label: "password", type: "password" },
},
//2. DB에서 아이디,비번 비교
async authorize(credentials) {
let db = (await connectDB).db('forum');
let user = await db.collection('user_cred').findOne({email : credentials.email})
if (!user) {
console.log('해당 이메일은 없는 이메일입니다.');
return null
}
const pwcheck = await bcrypt.compare(credentials.password, user.password);
if (!pwcheck) {
console.log('비밀번호가 일치하지 않습니다.');
return null
}
return user
}
})
],
adapter: MongoDBAdapter(connectDB),
secret: '1234'
};
export default NextAuth(authOptions);
1) credentitals : 로그인 페이지 폼 자동생성
2) authorize : DB 조회 후 비교
//3. jwt + jwt 만료일 설정
session: {
strategy: 'jwt',
maxAge: 30 * 24 * 60 * 60 //30일
},
callbacks: {
//4 JWT 토큰 생성
jwt: async ({ token, user }) => {
if (user) {
token.user = {};
token.user.name = user.name
token.user.email = user.email
}
return token;
},
//5. 유저 세션이 조회될 때 마다 실행되는 코드
session: async ({ session, token }) => {
session.user = token.user;
return session;
},
},
3) session : jwt 및 세션 만료일 설정
4) callbacks : jwt token 생성
5) session.user = token.user : 토큰을 유저에게 전달
소셜로그인 방식이 아닌 자체 로그인 기능을 JWT를 통해 만들어보았는데,
제일 신기했던 건 로그인 페이지 폼을 자동생성해 주는 기능이다.
필요한 입력값만 전달했을 뿐인데, 자동으로 input태그와 심지어 db체크 후 예외처리까지 동작한다.
하지만, 이 부분의 스타일을 바꿀 수 있는지 의문이다!
'Next.js' 카테고리의 다른 글
loading.js, error.js, not-found.js (0) | 2023.07.09 |
---|---|
.env 파일 <보안작업> (0) | 2023.07.08 |
Next-Auth + Session 방식 (0) | 2023.07.08 |
Next-Auth를 통한 소셜로그인 (0) | 2023.07.08 |
static rendering /dynamic rendering / cache (0) | 2023.07.07 |