Skip to content

Instantly share code, notes, and snippets.

@huy-tran
Created October 2, 2017 12:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save huy-tran/e10074b99a82f29eed70a16f6c530d4c to your computer and use it in GitHub Desktop.
Save huy-tran/e10074b99a82f29eed70a16f6c530d4c to your computer and use it in GitHub Desktop.
VueJS Auth Enquiry
// bootstrap.js
axios.interceptors.response.use(
response => {
/**
* If the response contains authorization header,
* Then we assume that it is from the renew token request.
* Set the new JWT token.
*/
const authHeader = response.headers.authorization;
if (authHeader) jwt.setToken(authHeader.substr(7));
return response;
},
error => {
const errorResponseData = error.response.data;
/**
* Expired token but still refreshable will hit this condition.
* We then trying to renew the expired token.
* Also passing the failed request as a callback to retry failed request.
*/
if (errorResponseData.message === 'Token has expired' && errorResponseData.statusCode === 401) {
return store.dispatch('auth/renewToken', error.response.config)
.then(response => {
if (response.status === 201 || response.status === 200) {
return Promise.resolve(response);
}
});
}
return Promise.reject(error);
}
);
// entry file (main.js)
store.dispatch('auth/getAuthUser')
.then(_ => {
return new Vue({
el: '#app', store, router,
});
})
.catch(_ => {
jwt.clearToken();
return new Vue({
el: '#app', store, router,
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment