vue实现登录不用token
Vue 实现无 Token 登录方案
在 Vue 中实现无 Token 登录通常依赖于传统的 Session-Cookie 机制或本地存储验证。以下是几种常见方法:
基于 Session-Cookie 的认证
后端需配置支持 Session,前端通过表单提交用户名密码:
// 登录请求示例
axios.post('/login', {
username: 'user',
password: 'pass'
}).then(response => {
// 后端会在响应头设置Set-Cookie
if (response.data.success) {
this.$router.push('/dashboard')
}
})
浏览器会自动管理 Cookie,后续请求会自动携带。需确保 withCredentials: true:
axios.defaults.withCredentials = true
本地存储用户状态
将登录状态保存在 localStorage 或 Vuex 中:
// 登录成功后存储状态
localStorage.setItem('isAuthenticated', 'true')
localStorage.setItem('username', 'user')
// 路由守卫检查
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !localStorage.getItem('isAuthenticated')) {
next('/login')
} else {
next()
}
})
基于 HTTP Basic Auth
通过 Base64 编码用户名密码(安全性较低,适合内部系统):
axios.get('/api', {
headers: {
'Authorization': 'Basic ' + btoa('user:pass')
}
})
服务端渲染(SSR)方案
使用 Nuxt.js 时可直接通过 req.session 管理:
// nuxtServerInit 动作
export const actions = {
async nuxtServerInit({ dispatch }, { req }) {
if (req.session.user) {
await dispatch('user/setUser', req.session.user)
}
}
}
安全注意事项
- 始终使用 HTTPS 传输敏感数据
- Session 需设置 HttpOnly 和 Secure 属性
- 考虑添加 CSRF 保护机制
- 敏感操作应进行二次验证
这些方案适用于不需要分布式认证的简单系统,对于需要更高安全性的场景仍推荐采用 Token 机制。







