728x90
반응형
1탄은 로그인을 인증하는 틀을 담았다. 2탄은 인증하기 위해 사용하는 JWT 토큰을 생성하는 과정이다.
JWT (JSON Web Token) 토큰을 만드는 방법을 React 애플리케이션과 Node.js 백엔드를 사용하여 구현하는 과정으로 나눴다.
- 백엔드 (Node.js) 설정: 사용자 인증 및 JWT 생성
- Express 서버 설정
- JWT 생성 및 검증
- 사용자 등록 및 로그인 엔드포인트 구현
- 프론트엔드 (React) 설정: 로그인 폼 및 JWT 저장 및 사용
- 로그인 폼 구현
- JWT를 이용한 인증 요청
- 보호된 리소스 접근
1. 백엔드 설정
Step 1: Node.js 프로젝트 초기화 및 필요 패키지 설치
먼저, Node.js 프로젝트를 초기화하고 필요한 패키지를 설치한다.
mkdir jwt-auth-example
cd jwt-auth-example
npm init -y
npm install express jsonwebtoken body-parser bcryptjs
설치하는 목록은 아래와 같은데 4가지 다 설치가 필수적이다.
express
: 웹 서버 프레임워크jsonwebtoken
: JWT 생성 및 검증body-parser
: 요청 바디를 파싱bcryptjs
: 비밀번호 해싱
Step 2: 서버 설정
server.js
파일을 생성하고나면 Express 서버를 설정해야 한다.
const express = require('express');
const jwt = require('jsonwebtoken');
const bodyParser = require('body-parser');
const bcrypt = require('bcryptjs');
const app = express();
const PORT = 5000;
app.use(bodyParser.json());
const users = [];
// JWT토큰 사인을 위한 Secret key를 저장하는 변수다.
const SECRET_KEY = '시크릿 키';
// endpoint 등록하는 과정이다.
app.post('/register', async (req, res) => {
const { username, password } = req.body;
const hashedPassword = await bcrypt.hash(password, 10);
users.push({ username, password: hashedPassword });
res.status(201).json({ message: '사용자 등록 성공!' });
});
// 로그인의 endpoint가 들어갈 부분이다.
app.post('/login', async (req, res) => {
const { username, password } = req.body;
const user = users.find(user => user.username === username);
if (!user) {
return res.status(401).json({ message: '잘못된 증명입니당' });
}
const isPasswordValid = await bcrypt.compare(password, user.password);
if (!isPasswordValid) {
return res.status(401).json({ message: '잘못된 증명입니당' });
}
const token = jwt.sign({ username: user.username }, SECRET_KEY, { expiresIn: '1h' });
res.json({ token });
});
// 보호된 경로 틀 예시
app.get('/protected', (req, res) => {
const authHeader = req.headers.authorization;
if (!authHeader) {
return res.status(401).json({ message: '받은 토큰이 없네용' });
}
const token = authHeader.split(' ')[1];
try {
const decoded = jwt.verify(token, SECRET_KEY);
res.json({ message: '보호된 데이터입니당', user: decoded });
} catch (error) {
res.status(401).json({ message: '잘못된 토큰입니당' });
}
});
// 콘솔에 찍어보깅
app.listen(PORT, () => {
console.log(`서버 돌아가는 중~ http://localhost:${PORT}`);
});
2. 프론트 설정
프론트 설정 과정은 로그인 구현1 링크를 확인해보면 된다.
728x90
반응형
'Front-end > React' 카테고리의 다른 글
리액트의 렌더링, 초기 렌더링, 그리고 Reconciliation (0) | 2024.11.11 |
---|---|
[React] 왜 리액트인가? 알아보자! 🤔 (1) | 2024.11.10 |
로그인 구현하기 - 4. 프론트와 백엔드의 협력 포인트 (1) | 2024.07.01 |
로그인 구현하기 - 3. 보안 조치와 안전성 높이기(Node.js, React) (0) | 2024.07.01 |
React로 로그인 기능 구현하기 (1): 프론트엔드 처리 과정 🚀 (0) | 2024.06.30 |