前后端分离后用户登录状态的保持和登录状态的安全保障

1.前后端分离后,前端登录状态保持一般采用webstorage或是cookie来保存token或用户信息的方式来维持登录状态。如果webstorage或是cookie中没有token,则前端认为是没有登录,拦截到登录页面。vue中利用路由的beforeEach实现,可在main.js中做如下逻辑:

// 路由判断登录 根据路由配置文件的参数
router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requireAuth)){ // 判断该路由是否需要登录权限

    if (localStorage.token) { // 判断当前的token是否存在 ; 登录存入的token
      next();
    }
    else {
      console.log('需要登录');
      next({
        path: '/login',
        query: {redirect: to.fullPath} // 将跳转的路由path作为参数,登录成功后跳转到该路由
      })
    }
  }
  else {
    next();
  }
});

router中配置,通过meta指定路由是否需要登录校验标识

export default new Router({
  routes: [
    {
      path: '/login',
      name: 'login',
      component: Login
    },
    {
      path: '/',
      name: 'App',
      meta:{
        requireAuth: true,
      },
      component:App,
      children:[
        {
          path: 'mycomp/xxx1',
          component: MyComp
        },
        {
          path: 'mycomp/xxx2',
          component: MyComp
        },
        {
          path: 'mycomp/xxx3',
          component: MyComp
        },
        {
          path: 'user/list',
          component: UserlIst
        }
      ]
    }

  ]
})

2.如上虽然利用localstorage实现了登录状态的校验。这里有个问题,如果用户在浏览器控制台手动往localstorage中添加一个token,然后就可以进入系统内的页面了。这是我们不希望的。如果想避免这种情况,必须依靠后端共同配合。即在上面判断localstorage中是否存在token,如果存在则把这个token发送到后台校验这个token是否正确,如果后台校验未通过则跳到登录界面

// 路由判断登录 根据路由配置文件的参数
router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requireAuth)){ // 判断该路由是否需要登录权限

    if (localStorage.token) { // 判断当前的token是否存在,存在则向后台发送校验
      let validateToken=调用后端接口校验localStorage.token;

          if(!validateToken){
            next({
            path: '/login',
            query: {redirect: to.fullPath} // 将跳转的路由path作为参数,登录成功后跳转到该路由
            });
          }
      next();
    }
    else {
      console.log('需要登录');
      next({
        path: '/login',
        query: {redirect: to.fullPath} // 将跳转的路由path作为参数,登录成功后跳转到该路由
      })
    }
  }
  else {
    next();
  }
});

3.上面2步控制了未登录时,无法访问系统内的页面。但对于页面上发起的请求并没有控制。比如在页面上有个按钮会像后台请求接口获取数据,这时后台返回token已经过期或是token校验未通过,我们希望用户被打入登录界面,进行登录。这时要用http请求的拦截器。比如vue项目中,请求使用的vue-resource,在main.js加入如下代码:

Vue.http.interceptors.push((request, next) => {
  //为所有请求添加token头
  if(localStorage.token){
    request.headers.set('Authorization', "Bearer "+localStorage.token);
  }

  //后端响应回来,首先进入这个next的回调函数中
  next((response) => {
    //如果后端返回401,则认为是token验证失败,跳转到登录页面
    if(response.status == 401){
      router.push("/login")
    }
    return response
  });
});

注意:vue项目对router、Vue.http等进行配置时,一定要在new Vue实例之前,否则加入的逻辑不生效

一般情况下,加1、3两步进行控制即可

你可能感兴趣的:(vue)