若要使用jwt cookie进行身份验证,您需要按照以下步骤做出配置:
在服务器端保存一个私钥,并使用此私钥对jwt进行签名。然后将jwt以cookie形式发送到客户端。
当访问需要身份验证的页面时,客户端会将请求cookie中的jwt发送到服务器端。
在服务器端,您需要使用相同的私钥验证jwt的签名是否有效。
验证通过后,在处理下一个中间件函数或路由处理函数之前,让传递给下一个函数的 request 对象附加用户身份信息。
以下是使用 Node.js 和 Express 框架实现上述步骤的基本代码示例:
const express = require('express'); const jwt = require('jsonwebtoken');
const app = express(); const secretKey = 'mysecretkey';
const authenticateJWT = (req, res, next) => { const token = req.cookies.jwt; if (token) { jwt.verify(token, secretKey, (err, user) => { if (err) { return res.sendStatus(403); } req.user = user; next(); }); } else { res.sendStatus(401); } };
app.use(express.json()); app.use(express.urlencoded({ extended: true })); app.use(cookieParser());
app.get('/', (req, res) => { res.send('Welcome to JWT cookie authentication example'); });
app.post('/login', (req, res) => { // Authentication logic here const user = { id: 1, username: 'testuser' }; const token = jwt.sign({ user }, secretKey); res.cookie('jwt', token); res.redirect('/dashboard'); });
app.get('/dashboard', authenticateJWT, (req, res) => {
res.send(Welcome ${req.user.username}
);
});
app.listen(3000, () => { console.log('Server is listening on port 3000'); });
上面的代码示例演示了如何创建并验证一个JWT令牌,并将其作为cookie发送和接收。 在/dashboard 路径上定义了一个受保护的路由,只有在用户经过身份验证才能访问。