Forked from fat4lix/gist:7a3f0f972ad2c3a4d45fed5e30d563e8
Last active
April 15, 2019 11:29
-
-
Save zombiQWERTY/bd3cbfed0052805db352e3586bf2ea63 to your computer and use it in GitHub Desktop.
Axios JWT interseptors
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 VueAxios from 'vue-axios'; | |
| import Vue from 'vue'; | |
| import {authService} from '@/store/modules/auth.module'; | |
| import {REFRESH_TOKEN_ENDPOINT} from '@/constants/endpoints'; | |
| import {LoginResponse} from '@/types/auth'; | |
| Vue.use(VueAxios, axios); | |
| axios.interceptors.request.use((request) => { | |
| const token = authService.getToken; | |
| if (token) { | |
| request.headers.common['Authorization'] = `Bearer ${token}`; | |
| } | |
| return request; | |
| }); | |
| axios.interceptors.response.use((response) => { | |
| return response; | |
| }, (error) => { | |
| if (error.config.url === REFRESH_TOKEN_ENDPOINT && | |
| (error.response.status === 401 || error.response.status === 404)) { | |
| authService.logout(); | |
| authService.setPerformRefresh(false); | |
| return new Promise((resolve, reject) => {reject(error); }); | |
| } | |
| if (error.response.status === 401 && authService.getToken && !authService.isPerformRefresh) { | |
| authService.setPerformRefresh(true); | |
| return axios.get<LoginResponse>(REFRESH_TOKEN_ENDPOINT).then(async (response) => { | |
| await authService.setToken(response.data.token, true); | |
| error.config.headers['Authorization'] = `Bearer ${response.data.token}`; | |
| authService.setPerformRefresh(false); | |
| return new Promise((resolve) => { | |
| resolve(axios(error.config)); | |
| }); | |
| }); | |
| } else { | |
| return new Promise((resolve, reject) => {reject(error); }); | |
| } | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment