laravel - User authentication ideas for Vue front-end single-page projects
滿天的星座
滿天的星座 2017-05-16 16:47:44
0
5
712

environment:

  • Backend: Laravel + Passport

  • Frontend:Vue 2.0 + Vuex + Vue-router

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! ! !

滿天的星座
滿天的星座

reply all(5)
Peter_Zhu

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;
PHPzhong

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.

Peter_Zhu

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

黄舟

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

大家讲道理

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}});
    }
  }
});
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template