tft每日頭條

 > 生活

 > oauth授權協議

oauth授權協議

生活 更新时间:2025-03-05 12:29:35

oauth授權協議?這篇文章主要是vue前端内容,對接後端進行登錄認證對應這上一篇springsecurity認證,包括以後的系列文章中會有的spring-security-oauth2後端認證,同樣都适用,我來為大家科普一下關于oauth授權協議?下面希望有你要的答案,我們一起來看看吧!

oauth授權協議(OAuth網絡安全登錄認證)1

oauth授權協議

這篇文章主要是vue前端内容,對接後端進行登錄認證。對應這上一篇springsecurity認證,包括以後的系列文章中會有的spring-security-oauth2後端認證,同樣都适用。

跟上一篇一樣,首先先說用戶登錄,我們需要調用後端的登錄接口,然後把返回的token信息,存儲在在cookie中。因為後邊項目中我們其他地方(比如登出lagout操作)可能需要直接獲取token,我們需要把token寫入到全局存儲store中。下邊是登陸方法:

Login({ commit }, userInfo) { const username = userInfo.username.trim()//用戶名 const password = userInfo.password //密碼 return new Promise((resolve, reject) => { login(username, password).then(res => { setToken(res.token) //token存入store中 commit('SET_TOKEN', res.token)//token存入cookie resolve() }).catch(error => { reject(error) }) }) },

然後在登錄的地方直接調用store裡的登錄方法。

this.$store.dispatch("Login", this.loginForm).then(() => { //登錄成功之後跳轉至首頁 this.$router.push({ path: this.redirect || "/" }).catch(()=>{}); }).catch(() => { //異常處理邏輯 });

下邊是前端跳轉路由的時候對token認證的一些處理,路由的鈎子函數beforeEach從cookie中取token,每次跳轉之前走beforeEach函數,判斷token是否存在,不存在,跳登錄頁,存在則拉取用戶信息,添加動态路由,并跳轉。以下是對應代碼。

router.beforeEach((to, from, next) => { NProgress.start() if (getToken()) {//判斷cookie是否有token if (to.path === '/login') { next({ path: '/' }) NProgress.done() } else { if (store.getters.roles.length === 0) { // 判斷當前用戶是否已拉取完user_info信息,獲取路由信息 router.addRoutes(accessRoutes) // 動态添加可訪問路由表 next({ ...to, replace: true }) // hack方法 确保addRoutes已完成 } else { next() } } } else { // 沒有token next(`/login`) // 否則全部重定向到登錄頁 NProgress.done() } })

最後也是最重要的,就是前端對後端進行接口請求的時候需要帶上token進行訪問,前端接口很多,每一個請求都加token的話,工作量大,而且是個很繁瑣的工作,對開發不利。需要把請求封裝一下,每個請求調用的時候自動添加token請求頭,用的是axios組件封裝請求。

// 創建axios實例 const service = axios.create({ // axios中請求配置有baseURL選項,表示請求URL公共部分 baseURL: process.env.VUE_APP_BASE_API, // 超時 timeout: 10000 }) // request攔截器 service.interceptors.request.use(config => { // 是否需要設置 token const isToken = (config.headers || {}).isToken === false if (getToken() && !isToken) { config.headers['Authorization'] = 'Bearer ' getToken() // 讓每個請求攜帶自定義token 請根據實際情況自行修改 } // get請求映射params參數 //此處代碼省略,僅作token講解 return config }, error => { console.log(error) Promise.reject(error) })

以上是對接後端登錄的關鍵代碼,請參考,其餘部分自己實現。

,

更多精彩资讯请关注tft每日頭條,我们将持续为您更新最新资讯!

查看全部

相关生活资讯推荐

热门生活资讯推荐

网友关注

Copyright 2023-2025 - www.tftnews.com All Rights Reserved