透過 JSON Web Token (JWT) 進行身份驗證廣泛用於保護 API 並確保只有授權使用者才能存取某些資料。在這篇文章中,我們將向您展示如何使用 Node.js 在後端配置 JWT,並使用 TypeScript 在 ReactJS 前端配置 JWT,從令牌產生到安全用戶會話管理。
首先,讓我們使用 Node.js、Express 和 TypeScript 建立一個 API,用於產生和驗證 JWT 令牌。
建立一個新專案並安裝主要依賴項:
npm init -y npm install express jsonwebtoken bcryptjs dotenv npm install -D typescript @types/node @types/express @types/jsonwebtoken @types/bcryptjs ts-node
為 TypeScript 配置建立 tsconfig.json 檔案:
{ "compilerOptions": { "target": "es6", "module": "commonjs", "outDir": "./dist", "strict": true, "esModuleInterop": true }, "include": ["src/**/*.ts"], "exclude": ["node_modules"] }
創建一個簡單的結構,從 server.ts 檔案和路由資料夾開始來組織身份驗證路由。
import express, { Application } from 'express'; import dotenv from 'dotenv'; import authRoutes from './routes/authRoutes'; dotenv.config(); const app: Application = express(); app.use(express.json()); app.use('/api/auth', authRoutes); const PORT = process.env.PORT || 5000; app.listen(PORT, () => console.log(`Servidor rodando na porta ${PORT}`));
建立身分驗證路由檔案。這裡我們將有一個登入路由來驗證使用者並返回 JWT 令牌。
import express, { Request, Response } from 'express'; import jwt from 'jsonwebtoken'; import bcrypt from 'bcryptjs'; const router = express.Router(); // Simulação de banco de dados const users = [{ username: 'usuario', password: 'senha123' }]; router.post('/login', async (req: Request, res: Response) => { const { username, password } = req.body; const user = users.find(u => u.username === username); if (!user || !(await bcrypt.compare(password, user.password))) { return res.status(401).json({ message: 'Credenciais inválidas' }); } const token = jwt.sign({ username }, process.env.JWT_SECRET as string, { expiresIn: '1h' }); res.json({ token }); }); export default router;
新增中間件以保護需要驗證的路由。
import { Request, Response, NextFunction } from 'express'; import jwt from 'jsonwebtoken'; interface JwtPayload { username: string; } export const authMiddleware = (req: Request, res: Response, next: NextFunction): void => { const token = req.headers['authorization']; if (!token) { res.status(403).json({ message: 'Token não fornecido' }); return; } jwt.verify(token, process.env.JWT_SECRET as string, (err, decoded) => { if (err) { res.status(401).json({ message: 'Token inválido' }); return; } req.user = decoded as JwtPayload; next(); }); };
在前端,我們將使用 React 來處理身份驗證、發送憑證和儲存 JWT 令牌。
首先,建立一個 Login.tsx 元件來擷取使用者的憑證並向後端發送登入請求。
import React, { useState } from 'react'; import axios from 'axios'; const Login: React.FC = () => { const [username, setUsername] = useState(''); const [password, setPassword] = useState (''); const [error, setError] = useState (''); const handleLogin = async (e: React.FormEvent) => { e.preventDefault(); try { const response = await axios.post('/api/auth/login', { username, password }); localStorage.setItem('token', response.data.token); window.location.href = '/dashboard'; } catch (err) { setError('Credenciais inválidas'); } }; return ( ); }; export default Login;
為受保護的路由建立一個函數,使用 JWT 令牌存取 API。
import React from 'react'; import { Route, Redirect, RouteProps } from 'react-router-dom'; interface PrivateRouteProps extends RouteProps { component: React.ComponentType; } const PrivateRoute: React.FC = ({ component: Component, ...rest }) => ( localStorage.getItem('token') ? ( ) : ( ) } /> ); export default PrivateRoute;
設定 axios 會自動在受保護的請求中包含 JWT 令牌。
import axios from 'axios'; const token = localStorage.getItem('token'); if (token) { axios.defaults.headers.common['Authorization'] = token; } export default axios;
現在,建立一個需要代幣才能存取的受保護頁面的範例。
import React, { useEffect, useState } from 'react'; import axios from './axiosConfig'; const Dashboard: React.FC = () => { const [data, setData] = useState(''); useEffect(() => { const fetchData = async () => { try { const response = await axios.get('/api/protected'); setData(response.data.message); } catch (error) { console.error(error); } }; fetchData(); }, []); return {data || 'Carregando...'}
; }; export default Dashboard;
透過這些步驟,我們在 TypeScript 中為一個在後端使用 Node.js 並在前端使用 React 的專案設定了完整的 JWT 身份驗證。這種方法高度安全、高效,並被廣泛採用來保護現代應用程式。
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3