搜尋

首頁  >  問答  >  主體

laravel - Vue前端單頁專案的使用者認證思路

環境:

#問題:

前端登陸後取得access_token,儲存在localStorage中,那麼使用者登出登入的話需要怎麼操作?清空localStorage嗎?是否需要再向後端發送請求?

如果用戶沒有點擊退出登錄,而是直接關閉瀏覽器或視窗呢,下次造訪時,localStorage裡的access_token依然存在,這樣的話安全性不太好吧?

我的access_token的有效期限是一年,那麼每次登入都會重新生成,這個怎麼解決?

求前端使用者認證的處理想法…萬分感謝! ! !

滿天的星座滿天的星座2822 天前748

全部回覆(5)我來回復

  • 天蓬老师

    天蓬老师2017-05-16 16:49:44

    剛好在做JWT的驗證,用axios和router做驗證,暫時還沒完成,先貼一部分程式碼參考

    axios部分

    import Vue from 'vue'
    import axios from 'axios'
    
    var http = axios.create({
      baseURL: process.env.API_URL
    });
    
    http.init = function () {
      http.interceptors.request.use(config => {
        this.load = true;
        if (localStorage.JWT_TOKEN) {
          config.headers = {'Authorization': localStorage.JWT_TOKEN};
        }
        return config;
      }, err => {
        this.load = false;
        console.error(err);
      });
      http.interceptors.response.use(res => {
        this.load = false;
        if (res.data.code === 1) {
          return res.data.data;
        } else {
          if (res.data.code == 4) {
            localStorage.removeItem('JWT_TOKEN');
            this.$router.push('/Login');
            alert(res.data.msg);
          } else if (res.data.code == 401) {
            localStorage.removeItem('JWT_TOKEN');
            this.$router.push('/Login');
          } else {
            throw new Error(res.data.msg);
          }
        }
      }, err => {
        this.load = false;
        throw new Error(res.data.msg);
      });
    }
    
    Vue.prototype.$http = http;
    

    router部分:

    import Vue from 'vue'
    import Router from 'vue-router'
    
    function include (name) {
      return resolve => require(['components/' + name], resolve);
    }
    
    function route (name) {
      return {
        name: name,
        path: name,
        component: include(name)
      }
    }
    
    Vue.use(Router);
    
    var router = new Router({
      base: '/admin/',
      mode: 'history',
      routes: [
        {
          name: 'Index',
          path: '/',
          component: include('Index'),
          children: [
            {
              name: 'User',
              path: 'User/:page/:rows',
              component: include('User')
            }
          ]
        },
        {
          name: 'Login',
          path: '/Login',
          component: include('Login')
        },
        {
          path: '*',
          redirect: '/'
        }
      ]
    })
    
    router.beforeEach(({name}, from, next) => {
      if (localStorage.JWT_TOKEN) {
        if (name == 'Login') {
          next('/');
        } else {
          next();
        }
      } else {
        if (name == 'Login') {
          next();
        } else {
          next({name: 'Login'});
        }
      }
    });
    
    export default router;
    

    回覆
    0
  • PHPz

    PHPz2017-05-16 16:49:44

    退出時刪除localStorage中的access_token
    可以给Vuex写个插件,每次commit mutation时,更新一下access_token的刷新時間。
    下次登入時,判斷這個刷新時間,5分鐘前了,就認為登入資訊過期了。

    如果不想把access_token放到localStorage中,可以放在Vuex中,每次都需要重新登入。 access_token放到localStorage中,可以放在Vuex中,每次都需要重新登录。
    重新登录时,你可以没必要都重新生成access_token重新登入時,你可以沒必要都重新產生access_token吧。

    回覆
    0
  • 天蓬老师

    天蓬老师2017-05-16 16:49:44

    剛好總結了一個項目,歡迎star~
    【vue+axios】一個項目學會前端實現登入攔截

    回覆
    0
  • 黄舟

    黄舟2017-05-16 16:49:44

    認證資訊以後台為準,不管是登入或登出都要傳送請求,然後根據api回傳的結果前端進行操作,如果不記住認證資訊用sesionStorage好點

    回覆
    0
  • 大家讲道理

    大家讲道理2017-05-16 16:49:44

    設定路由的攔截器,攔截除了login和logout的所有頁面,檢查本地變數user是否存在,存在則判斷上次校驗時間,如果超出1分鐘則重新校驗。

    router.beforeEach((to, from, next) => {
      // to 和 from 都是 路由信息对象
      //var auth = to.matched[0].default.auth;
      //console.log(to);
      if (to.path =="/login" || to.path =="/logout") {
        next();
      }
      else {
        const user = store.state.system.user;
        if(user){
          const time = new Date().getTime();
          if(time-user.lastCheckTime > 60*1000){ // 如果上次检查时间大于1分钟,则调用服务端接口判断session 是否依然有效
            store.dispatch("checkLogin",(error,isLogined)=>{ // 异步检查是否状态有效
              if(error || !isLogined){
                console.warn("登录超时");
                next({'path':'/login',query:{backUrl:to.fullPath}});
              }
              else{
                next();
              }
            });
          }
          else{
            next();
          }
    
        }
        else{
          console.warn("需要登录");
          next({'path':'/login',query:{backUrl:to.fullPath}});
        }
      }
    });

    回覆
    0
  • 取消回覆