导入
在 Node.js 中实现身份验证
学习如何使用 bcrypt 进行密码哈希,并通过 JSON Web Tokens (JWT) 实现无状态认证,在 Node.js 中实现安全的身份验证。
...
Password hashing using bcrypt library
No configuration found for ID: ea5934916f8c3d13cbe9790efc88d41e3d0ee473092bfd0588c442dcc9f2782a
1// Inside the POST /register handler 2let body = ''; 3req.on('data', (chunk) => (body += chunk.toString())); 4req.on('end', async () => { 5 const { username, password } = JSON.parse(body); 6 7 const hashedPassword = await bcrypt.hash(password, 10); 8 9 console.log(`User: ${username}, Hashed Password: ${hashedPassword}`); 10 res.writeHead(201, { 'Content-Type': 'text/plain' }); 11 res.end('User registered successfully!'); 12});
1.
How is the password kept safe when sent from the client to the server in the POST body?
0/500
...
How JWT authentication works
1// Inside the POST /login handler 2const storedHashedPassword = 'stored_hashed_password'; 3const isMatch = await bcrypt.compare(password, storedHashedPassword); 4if (isMatch) { 5 const token = jwt.sign({ username }, secretKey, { expiresIn: '1h' }); 6 res.writeHead(200, { 'Content-Type': 'application/json' }); 7 res.end(JSON.stringify({ message: 'Login successful', token })); 8} else { 9 res.writeHead(401, { 'Content-Type': 'text/plain' }); 10 res.end('Invalid credentials'); 11}
1import jwt from 'jsonwebtoken'; 2import { createServer } from 'http'; 3 4const secretKey = 'secret_key'; 5 6const authenticateJWT = (req, res, next) => { 7 const authHeader = req.headers['authorization']; 8 const token = authHeader && authHeader.split(' ')[1]; 9 10 if (!token) { 11 res.writeHead(401, { 'Content-Type': 'text/plain' }); 12 return res.end('Access denied'); 13 } 14 15 jwt.verify(token, secretKey, (err, user) => { 16 if (err) { 17 res.writeHead(403, { 'Content-Type': 'text/plain' }); 18 return res.end('Invalid token'); 19 } 20 21 req.user = user; 22 next(); 23 }); 24}; 25 26const server = createServer((req, res) => { 27 if (req.method === 'GET' && req.url === '/profile') { 28 authenticateJWT(req, res, () => { 29 res.writeHead(200, { 'Content-Type': 'text/plain' }); 30 res.end(`Welcome, ${req.user.username}`); 31 }); 32 } else { 33 res.writeHead(404, { 'Content-Type': 'text/plain' }); 34 res.end('Not Found'); 35 } 36}); 37 38server.listen(3000, () => { 39 console.log('Server running on http://localhost:3000'); 40});
No configuration found for ID: 8a1c1f7ee687a73b38b24a03be9ac9588d1a458c2f67ba6b34bce815ced2b5a1
1curl -X POST http://localhost:3000/register \ 2-H "Content-Type: application/json" \ 3-d '{"username": "testUser", "password": "securePassword123"}'
1curl -X POST http://localhost:3000/login \ 2-H "Content-Type: application/json" \ 3-d '{"username": "testUser", "password": "securePassword123"}'
1{ 2 "message": "Login successful", 3 "token": "<JWT_TOKEN>" 4}
1curl -X GET http://localhost:3000/profile \ 2-H "Authorization: Bearer <JWT_TOKEN>"
代码示例
1Welcome, testUser