簡體   English   中英

如何保護 Vue.js 中的客戶端路由?

[英]How to protect client side routes in Vue.js?

我現在正在構建一個使用 Vue.js 作為前端框架的水療中心,它與使用 jsonwebtokens 的純 json 后端進行通信。 我更熟悉 React 生態系統。 我目前不確定如何保護 Vue.js 中的客戶端路由。 (不是我對框架的決定。我是新員工。耶!)

作為反應,我會做這樣的事情。 在項目的 index.js 文件中。 在應用掛載之前檢查本地存儲中是否有 jsonwebtoken。 如果有,將 redux 狀態設置為登錄。如果沒有設置為注銷。

然后我會使用高階組件來保護我的路由,這樣每當用戶嘗試進入客戶端受保護的路由時,我都會使用 componentWillMount 生命周期方法來檢查登錄狀態。 如果已登錄,則呈現組件。 否則重定向到登錄頁面。

似乎 vue 中的高階組件無法實現相同的行為。 或者我只是找不到向我展示如何實現它的文檔。 有人可以與我分享他們如何解決這個問題嗎?

文檔中所述,您可以在要檢查身份驗證的所有路由上使用元字段

文檔中提供的示例:

router.beforeEach((to, from, next) => { 
    if (to.matched.some(record => record.meta.requiresAuth)) { 
        // this route requires auth, check if logged in 
        // if not, redirect to login page. 
        if (!auth.loggedIn()) { 
            next({ 
                path: '/login', 
                query: { redirect: to.fullPath } 
            }) 
        } else { 
            next() 
        } 
    } else { 
        next() // make sure to always call next()! 
    } 
}) 

或者對於組件導航守衛,您可以按照 wostex 提供的第二個鏈接

這是使用 Vue.js 實現身份驗證的一個很好的例子:鏈接

更具體地說,這里是關於導航的手冊。 守衛:鏈接

我想我錯過了路由元字段的文檔。 我在做一些愚蠢的事情,但我想我在工作。 哈哈。

router.beforeEach((to, from, next) => {
    let web = ["home", "login", "verifyAccount", "resetPassword","forgotPassword","register"];
    if(web.includes(to.name)){
        next();
    }else{
        axios.post('/api/auth/verify-token',{
            token: localStorage.token
        }).then(response=>{
            if(response.data.verification === true){
                next();
            }else{
                router.push({
                    name:'home',
                    params:{
                        serverError:true,
                        serverMsg: 'Please login to continue.'
                    }
                });
            }
        }).catch(response=> {
            console.log(response);
        });
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM