使用 jwt 身份验证自动登录 vue 应用程序

auto login on vue application with jwt authentication

我使用 jwt 令牌授权操作并从我的后端请求受保护的资源。

前端:Vue、Vue 路由器、VueX、Vuetify

后端: Express, jwt tokens, cookieParser

如果我成功调用登录路由,accessToken 和用户数据(用户名、电子邮件、userId)将被传送回前端。除此之外,我还发回了一个 httpOnly cookie(包含 refreshToken)并将 refreshToken 插入到我的数据库的另一端。通过 vuex 存储,我将 state.loggedIn 触发到 true,并将 user 对象分配给 state.user。在同一个函数中,我将 user 对象保存到我的 localStorage。

要知道在重新打开新标签页,关闭window等后是否应该自动登录用户。我读取了localStorage的数据并在[=17开头启动了vueX存储=] 和 user.

// read out localStorage for the user
const user = JSON.parse(localStorage.getItem('user'));

const initialState = user
    ? { user, loggedIn: true, accessToken: null }
    : { user: null, loggedIn: false, accessToken: null };

在调用受保护的路由之前,我在 vue 路由器对象上使用 beforeEach 方法来检查我的 vueX getter auth/getUser returns 是否是用户对象。如果没有,vue router 会重定向到登录页面,这样用户就可以重新授权自己了。

const routes = [
  { path: '/login', name: 'Login', component: Login, meta: { authRequired: false }},
  { path: '/home', name: 'Home', component: Home, meta: { authRequired: true }}
]

const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes });

router.beforeEach(async (to, from, next) => {
  if (to.meta.authRequired) {
    let user = VuexStore.getters['auth/getUser'];
    if (!user) {
      next({ path: '/login'});
    }
  }
  next();
});

可是,谁保证localStorage中的user对象是合法的,而不是直接设置为true。这是要走的路,还是我应该以任何方式将收到的 accessToken 或带有 refreshToken 的 cookie 用于自动登录过程?谢谢。

是的,你快到了。您正在寻找的是刷新令牌:

https://hasura.io/blog/best-practices-of-using-jwt-with-graphql/#silent_refresh https://auth0.com/blog/refresh-tokens-what-are-they-and-when-to-use-them/

本质上,您希望在当前令牌过期时在 localStorage 中进行跟踪。然后在即将刷新时在后台自动刷新令牌。所以用户不会自动注销。

编辑添加:

But, who guarantees that the user object in the localStorage is valid and not just set to true. Is this the way to go, or should I use the received accessToken or the cookie with the refreshToken in any way for the auto login process? Thanks.

您的 API 可以保证这一点。第二个用户将尝试使用无效的访问令牌与您的 API 交互,您的 API 会抛出错误。它不会工作。因此,如果用户开始弄乱客户端数据,那也没关系。永远不要相信服务器端 ;-)