Created
July 10, 2019 14:20
-
-
Save sidigi/af90ce5a7f0d2412636d898b5871dfa6 to your computer and use it in GitHub Desktop.
Nuxt Refresh token request
This file contains 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
export default function ({$axios, app}) { | |
$axios.onResponseError(error => { | |
const code = parseInt(error.response && error.response.status); | |
let originalRequest = error.config; | |
if ([401, 403].includes(code)) { | |
originalRequest.__isRetryRequest = true; | |
let refresh_token = app.$auth.getRefreshToken(app.$auth.$storage.state.strategy).replace('Bearer ', ''); | |
return new Promise((resolve, reject) => { | |
$axios | |
.post(`http://bgs-auth.local/api/refresh-token`, {refresh_token}) | |
.then(response => { | |
if (response.status == 200) { | |
app.$auth.setToken(app.$auth.$storage.state.strategy,'Bearer ' + response.data.access_token); | |
app.$auth.ctx.app.$axios.setHeader('Authorization', 'Bearer ' + response.data.access_token); | |
app.$auth.setRefreshToken(app.$auth.$storage.state.strategy, 'Bearer ' + response.data.refresh_token); | |
originalRequest.headers['Authorization'] = `Bearer ${response.data.access_token}`; | |
} | |
resolve(response); | |
}) | |
}) | |
.then(res => { | |
return $axios(originalRequest); | |
}).catch(e => { | |
app.$auth.logout(); | |
setTimeout(() => { | |
app.router.push('/login'); | |
}) | |
}); | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment