vue实现jwt
Vue 中实现 JWT 认证的步骤
安装依赖
需要安装 jsonwebtoken 和 axios 用于生成/验证 Token 和发起 HTTP 请求:
npm install jsonwebtoken axios
后端生成 JWT Node.js 后端示例(如 Express)生成 Token:
const jwt = require('jsonwebtoken');
const secret = 'your-secret-key';
app.post('/login', (req, res) => {
const user = { id: 1, username: 'example' };
const token = jwt.sign(user, secret, { expiresIn: '1h' });
res.json({ token });
});
前端存储 Token 登录成功后存储 Token 至 localStorage 或 Vuex:
axios.post('/login', credentials)
.then(response => {
localStorage.setItem('jwt_token', response.data.token);
});
请求拦截器 通过 axios 拦截器在请求头添加 Token:
axios.interceptors.request.use(config => {
const token = localStorage.getItem('jwt_token');
if (token) config.headers.Authorization = `Bearer ${token}`;
return config;
});
Token 验证
前端可通过 jwt-decode 解析 Token 判断是否过期:
import jwtDecode from 'jwt-decode';
const token = localStorage.getItem('jwt_token');
if (token) {
const decoded = jwtDecode(token);
const isExpired = decoded.exp < Date.now() / 1000;
if (isExpired) localStorage.removeItem('jwt_token');
}
路由守卫 Vue Router 中配置全局前置守卫保护路由:
router.beforeEach((to, from, next) => {
const isAuthenticated = localStorage.getItem('jwt_token');
if (to.meta.requiresAuth && !isAuthenticated) next('/login');
else next();
});
注意事项
- 敏感操作需后端二次验证 Token 有效性
- 避免在 Token 中存储敏感信息
- HTTPS 环境下使用 JWT
- 设置合理的 Token 过期时间







