Created
May 19, 2019 06:16
-
-
Save cryocaustik/366b9a5ce6ffc44cdeacbaaad8f434ce to your computer and use it in GitHub Desktop.
Vuex + axios interceptors to to attach JWT auth tokens to requests, and trigger token refreshes on 401 errors
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
import axios from 'axios' | |
import store from '@/store' | |
export default function setup() { | |
/** | |
* Intercept axios request and attach JWT tokens as authorization | |
*/ | |
axios.interceptors.request.use( | |
config => { | |
if (!config.url.endsWith('/refresh')) { | |
if (config.headers.Accept) { | |
config.headers.Accept = 'application/json, ' + config.headers.Accept | |
} else { | |
config.headers.Accept = 'application/json' | |
} | |
config.headers['Authorization'] = `Bearer ${store.state.jwt}` | |
} | |
return config | |
}, | |
err => { | |
console.log('interceptor: error ', err.config) | |
return err | |
} | |
) | |
/** | |
* Intercept axios responses and on 401s, trigger token refresh, and then retry the original request. | |
*/ | |
axios.interceptors.response.use(null, err => { | |
if ( | |
err.config && | |
!err.config.url.endsWith('/refresh') && | |
err.response.status === 401 && | |
store.getters.isLoggedIn && | |
store.state.refreshAttempts < 3 | |
) { | |
store.state.refreshAttempts += 1 | |
return store.dispatch('refreshToken').then(() => { | |
store.state.refreshAttempts = 0 | |
return new Promise((resolve, reject) => { | |
axios | |
.request(err.config) | |
.then(resp => { | |
resolve(resp) | |
}) | |
.catch(err => { | |
reject(err) | |
}) | |
}) | |
}) | |
} else { | |
return err | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment