在vue中使用後臺提供的token驗證方式總結及使用方法

token是相對會叫安全的使用暗碼形式的數據傳輸,由後臺產生,並且傳輸到前臺,前臺可以將保存,在前臺每次發送請求的時候可以攜帶token,後臺可以對token進行驗證,通過驗證的通過請求可以對數據進行正確的回覆,否則就睡返回錯誤的回執碼

token有自己的過期時限,並且是在後臺實現,前臺虛無考慮那麼多,具體前臺的步驟分爲三部

1.在登陸的時候後臺會給一個token碼,前臺將其存儲在cookie,localstroage或者localsession中即可

請注意需要在tooken的前邊拼接字符串'Bearer '+,固定格式

login(){
    axios.post('/user/login',this.user).then((res)=>{
        localStorage.setItem('token',"Bearer "+res.data.res.token)
    })
}

2.在router中設置守衛導航

判斷token是否存在,如果存在將攜帶token進行下一簇的操作,如果不存在,則返回登陸

router.beforeEach((to,from,next)=>{
    if(to.matched.some((route)=>route.meta.Auth)){
        if(localStorage.getItem('token')){
            next()
        }else{
             next({
                path:'/login',
                query:{
                    returnURL:to.path
                }
            })
        }
       
    }else{
         next()
    }
   
})

3.在axios的請求攔截器中攜帶tooken進行請求

axios.interceptors.request.use(config=>{
    const token=localStorage.getItem('token')
    // if(token){
        token?config.headers.Authorization=token:null;
    // }
    return config
});

每次請求時都會攜帶token,後臺驗證不驗證token就是後臺的問題了

設置token的回覆攔截器,對回執碼錯誤的進行操作處理

axios.interceptors.response.use(res=>{
    if(res.data.res_code=== 401){
        router.replace('/login');
        localStorage.removeItem('token')
    }
    return res
})

這個根據後臺的回執碼自行更改就行

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章