当访问令牌到期时,我们如何保持用户登录,我们需要再次登录才能以普通用户身份继续 [英] How can we maintain user logged in when access token expires and we need to login again to continue as normal user

查看:196
本文介绍了当访问令牌到期时,我们如何保持用户登录,我们需要再次登录才能以普通用户身份继续的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将 Nuxt-axios 模块与代理一起使用.

I'm using Nuxt-axios module with the proxy.

对于错误处理,我有通用代码

For Error handling, I have common code in

插件/axios.js

export default function({ $axios, __isRetryRequest, store, app, redirect , payload , next}) {
  $axios.onRequest(config => {
  if (app.$cookies.get('at') && app.$cookies.get('rt') && config.url != '/post_login/') {
      config.headers.common['Authorization'] = `Bearer ${app.$cookies.get('at')}`;
    }
  });

  $axios.onResponseError(err => {
    const code = parseInt(err.response && err.response.status)

    let originalRequest = err.config;

    if (code === 401) {
      originalRequest.__isRetryRequest = true;

      store
        .dispatch('LOGIN', { grant_type: 'refresh_token', refresh_token: app.$cookies.get('rt')})
        .then(res => {
          originalRequest.headers['Authorization'] = 'Bearer ' + app.$cookies.get('at');
          return app.$axios(originalRequest);
        })
        .catch(error => {
          console.log(error);
        });
    }

    // code for 422 error
    if (code == 422) {
      throw err.response;
    }

  });
}

在我的页面文件夹索引页面上

On my page folder index page

Pages/index.vue

<template>
  <section>Component data</section>
</template>

<script type="text/javascript">
export default {
  async asyncData({ route, store }) {
    await store.dispatch('GET_BANNERS');
  }
}
</script>

所有API调用都位于stroes/actions.js文件中.

All the API calls are in a stroes/actions.js file.

现在的问题是何时刷新页面索引.如果成功,第一个API请求将会命中并获得响应.但是现在,如果在asyncData的第一个请求("GET_BANNERS")上得到未经授权的401错误,那么我将得到错误提示

Now the question is when I refresh the page index.vue first API request will hit and get the response if successful. But now if on first request( 'GET_BANNERS' ) from asyncData and it gets 401 error unauthorized then I'm getting below error

Error: Request failed with status code 401

错误[ERR_HTTP_HEADERS_SENT]:将标头发送到客户端后无法设置标头

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

我该如何解决?

还有几个问题:

1)当我在axios中编写常见错误代码时,收到401的原始请求如何设置要再次存储的数据(通常我们从动作文件中进行存储)?

1) When I'm writing common error code in axios, original request on which I have received 401 how can I set data to store again(which we normally do from actions file)?

2)任何人都可以通过最佳实践来为400,401,422等附加授权标头和错误句柄.

2) can anyone help with best practice to attach authorization headers and error handle for 400,401,422, etc..

推荐答案

$axios.onResponseError(err => {
  const code = parseInt(err.response && err.response.status);

  let originalRequest = err.config;
  if (code == 401) {
    originalRequest.__isRetryRequest = true;

    let token = app.$cookies.get('rt');

    return new Promise((resolve, reject) => {
      let req = $axios
        .post(`/login`, { grant_type: 'refresh_token', refresh_token: token })
        .then(response => {

          if (response.status == 200) {

              app.$cookies.set('access', response.data.access_token);
              app.$cookies.set('refresh', response.data.refresh_token);
              originalRequest.headers['Authorization'] = `Bearer ${
                response.data.access_token
              }`;
          }
          resolve(response);
        }).catch(e => {
          reject("some message");
        })

      })
      .then(res => {
        return $axios(originalRequest);
      }).catch(e => {
        app.router.push('/login');
      });
  }
});

@ canet-robern希望这能解决您的问题!!

@canet-robern hope this will solve your prob!!

这篇关于当访问令牌到期时,我们如何保持用户登录,我们需要再次登录才能以普通用户身份继续的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆