How can we maintain user logged in when access token expires and we need to login again to continue as normal user

孤者浪人 提交于 2020-01-24 19:33:07

问题


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

For Error handling, I have common code in

Plugins/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>

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

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

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

how can I resolve this?

few more questions:

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) can anyone help with best practice to attach authorization headers and error handle for 400,401,422, etc..


回答1:


$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 hope this will solve your prob!!




回答2:


The error ERR_HTTP_HEADERS_SENT means that you have a bug in your server-side code - hence the error from this bug comes before the HTTP headers.

To handle 4xx errors and retry the Axios request - follow this example:

Vue.prototype.$axios = axios.create(
  {
    headers:
      {
        'Content-Type': 'application/json',
      },
    baseURL: process.env.API_URL
  }
);

Vue.prototype.$axios.interceptors.request.use(
  config =>
  {
    events.$emit('show_spin');
    let token = getTokenID();
    if(token && token.length) config.headers['Authorization'] = token;
    return config;
  },
  error =>
  {
    events.$emit('hide_spin');
    if (error.status === 401) VueRouter.push('/login');
    else throw error;
  }
);
Vue.prototype.$axios.interceptors.response.use(
  response =>
  {
    events.$emit('hide_spin');
    return response;
  },
  error =>
  {
    events.$emit('hide_spin');
    return new Promise(function(resolve,reject)
    {
      if (error.config && error.response && error.response.status === 401 && !error.config.__isRetry)
      {
        myVue.refreshToken(function()
        {
          error.config.__isRetry = true;
          error.config.headers['Authorization'] = getTokenID();
          myVue.$axios(error.config).then(resolve,reject);
        },function(flag) // true = invalid session, false = something else
        {
          if(process.env.NODE_ENV === 'development') console.log('Could not refresh token');
          if(getUserID()) myVue.showFailed('Could not refresh the Authorization Token');
          reject(flag);
        });
      }
      else throw error;
    });
  }
); 


来源:https://stackoverflow.com/questions/51230501/how-can-we-maintain-user-logged-in-when-access-token-expires-and-we-need-to-logi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!