如何检查 JWT 令牌有效性

How to check JWT token validity

我一直在关注 this tutorial to make an authentification with lumen and vuejs. I'm using this 图书馆 (tymon/jwt-auth)。

一切正常。我的 API 处理我的数据的所有事情,并为我的前端框架提供一个令牌。我可以 login/logout 并且我需要一个有效令牌来发送 API 请求。

Vuex中有这个常数:

const state = {
    isLogged: !!localStorage.getItem('token')
}

它正在检查是否有令牌,如果没有,将其设置为 false 并重定向到登录页面。但是如果我手动向我的 cookie 添加一个令牌,我可以从我的 vue-router 访问每条路由并查看静态数据。当然,来自 API 的数据将不可用,但 如果令牌未验证(用户未登录),我不想访问此路由。

我该如何处理?我是否必须每次都通过 ajax 电话进行检查?我实际上正在使用这个:

router.beforeEach((to, from, next) => {
    const auth = store.state.auth;

    if (to.name == "logout" || to.name == "login") {
        next();
    } else {
        if (store.state.isLogged) {
            next();
        } else {
            next('/');
        }
    }
})

我认为唯一的解决方案是 Ajax 调用,因为我们无法在 vuejs 中验证,不是吗?

无法在本地检查您的令牌。你必须明白,你不能相信来自用户计算机的任何东西。

您需要做的是在每个路由之前发送一个 ajax 请求,以便检查您的令牌是否仍然有效。