search

Home  >  Q&A  >  body text

laravel - User authentication ideas for Vue front-end single-page projects

environment:

question:

After logging in, the front-end obtains access_token and saves it in localStorage. What should the user do if they log out? Clear localStorage? Do I need to send another request to the backend?

If the user does not click to log out, but directly closes the browser or window, the access_token in localStorage will still exist the next time he visits, which is not very secure. All right?

My access_token is valid for one year, so it will be regenerated every time I log in. How to solve this problem?

Looking for ideas on how to handle front-end user authentication... Thank you very much! ! !

滿天的星座滿天的星座2827 days ago753

reply all(5)I'll reply

  • 天蓬老师

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

    I just happened to be doing JWT verification, using axios and router for verification. It is not completed yet, so I will post some code for reference

    axios part

    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 part:

    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;
    

    reply
    0
  • PHPz

    PHPz2017-05-16 16:49:44

    Delete the localStorage中的access_token
    可以给Vuex写个插件,每次commit mutation时,更新一下access_token refresh time when exiting.
    The next time you log in, determine the refresh time. If it is 5 minutes ago, the login information will be considered expired.

    If you don’t want to put access_token in localStorage, you can put it in Vuex, and you need to log in again every time. access_token放到localStorage中,可以放在Vuex中,每次都需要重新登录。
    重新登录时,你可以没必要都重新生成access_tokenWhen logging in again, you don’t need to regenerate access_token.

    reply
    0
  • 天蓬老师

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

    I just summarized a project, welcome to star~
    [vue+axios] A project to learn how to implement login interception on the front end

    reply
    0
  • 黄舟

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

    The authentication information is subject to the background. Whether you are logging in or logging out, you must send a request, and then operate the front end based on the results returned by the api. If you do not remember the authentication information, it is better to use sessionStorage

    reply
    0
  • 大家讲道理

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

    Set a routing interceptor, intercept all pages except login and logout, check whether the local variable user exists, if it exists, determine the last verification time, and re-verify if it exceeds 1 minute.

    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}});
        }
      }
    });

    reply
    0
  • Cancelreply