Skip to content

Commit

Permalink
Handle 401 token errors (#62)
Browse files Browse the repository at this point in the history
  • Loading branch information
carlosthe19916 authored Jun 18, 2024
1 parent 9958c11 commit f7e73fa
Showing 1 changed file with 29 additions and 2 deletions.
31 changes: 29 additions & 2 deletions client/src/app/axios-config/apiInit.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import axios from "axios";
import { User } from "oidc-client-ts";
import { User, UserManager } from "oidc-client-ts";

import { OIDC_CLIENT_ID, OIDC_SERVER_URL } from "@app/oidc";
import { OIDC_CLIENT_ID, OIDC_SERVER_URL, oidcClientSettings } from "@app/oidc";

function getUser() {
const oidcStorage = sessionStorage.getItem(
Expand All @@ -28,4 +28,31 @@ export const initInterceptors = () => {
return Promise.reject(error);
}
);

axios.interceptors.response.use(
(response) => {
return response;
},
async (error) => {
if (error.response && error.response.status === 401) {
const userManager = new UserManager(oidcClientSettings);
try {
const refreshedUser = await userManager.signinSilent();
const access_token = refreshedUser?.access_token;
const retryConfig = {
...error.config,
headers: {
...error.config.headers,
Authorization: `Bearer ${access_token}`,
},
};
return axios(retryConfig);
} catch (refreshError) {
await userManager.signoutRedirect();
}
}

return Promise.reject(error);
}
);
};

0 comments on commit f7e73fa

Please sign in to comment.