Created
October 2, 2017 12:59
-
-
Save huy-tran/e10074b99a82f29eed70a16f6c530d4c to your computer and use it in GitHub Desktop.
VueJS Auth Enquiry
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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