javascript - Login interception logic problem?
PHP中文网
PHP中文网 2017-05-16 13:31:56
0
2
564

Now I enter my account password, the browser sends a request, and the token is returned successfully;

What I want to ask is: Should I put this token in a cookie or in localStorage?

Also, how to deal with login interception on other pages?

Is it necessary to determine if there is a token in the cookie or localStorage and then release it?
(If so, others can just create a token and let it go)

And how to use the successfully returned timeout period? Is it placed in the cookie?

Or is my thinking wrong?

PHP中文网
PHP中文网

认证高级PHP讲师

reply all(2)
某草草

After the user authentication is successful, the token 值,前端一般存在 localStorage 里。
每次发出请求的时候,把该 token 放在请求头即可。
下面以 axios returned by the server is as an example:


// http request 拦截器
api.interceptors.request.use(config => {
  if (window.localStorage.ACCESS_TOKEN) {
    config.headers.Authorization = 'Bearer ' + window.localStorage.ACCESS_TOKEN
  }
  return config
}, error => {
  return Promise.reject(error)
})

// http response 拦截器
api.interceptors.response.use(response => {
  if (response.status === 401) { // token过期
    window.localStorage.removeItem('ACCESS_TOKEN')
    router.replace({
      path: '/user/login',
      query: {
        redirect: router.currentRoute.fullPath
      }
    })
  }
  return response
}, error => {
  return Promise.reject(error)
})
The login interception of the

page takes vue.jsvue-router as an example:

// 导航钩子
router.beforeEach((to, from, next) => {
  // 检查登录状态
  store.commit(types.CHECKOUT_LOGIN_STATUS)
  if (to.matched.some(record => record.meta.requiresAuth)) { // 判断该路由是否需要登录权限
    if (window.localStorage.ACCESS_TOKEN) { // 如果本地存在 access_token,则继续导航
      next()
    } else {
      if (name === 'userLogin') {
        next()
      } else {
        next({ // 登录成功后,自动跳转到之前的页面
          path: '/user/login',
          query: {
            redirect: to.fullPath
          }
        })
      }
    }
  } else {
    next()
  }
})

Also token 值一般是很难伪造的,因为每次请求都会向后端去验证该 token the validity of the value.

PHPzhong

It is recommended to use setCookie in the request returned by the server to set the token, and set it to httpOnly. Bring cookies in subsequent requests, and then determine the status based on the server's callback.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!