When developing an application and trying to use a refresh token, I am encountering an issue. Authentication is done using ADFS which provides an id_token that expires hourly and a refresh token that lasts 8 hours.
The script below works flawlessly in development mode for refreshing the tokens.
However, in production, while new tokens are obtained, the original request is never retried. The difference in behavior between webpack-dev-server and production is what I am trying to figure out.
Any assistance on this matter would be greatly appreciated!
P.S. Babel Presets Being Used: babel-preset-env and babel-preset-stage-2
axios.js
import axios from 'axios'
// Set baseURL based on environment
const baseURL = process.env.NODE_ENV === 'development' ? '//localhost:3001/api' : '/api'
// Create axios instance with correct baseURL
const instance = axios.create({
baseURL
})
// Intercept responses
instance.interceptors.response.use((response) => {
return response
}, async (error) => {
// Extract config, status and data from the error
const { config, response: { status, data } } = error
// Retrieve tokens from local storage
let currentTokens = JSON.parse(localStorage.getItem('tokens')) || null
// Check if response errors at 401, token is valid and we have tokens in localStorage
if(status === 401 && data.token_invalid === undefined && currentTokens && !config._retry) {
config._retry = true
try {
// Request new token from server
const authenticate = await instance.post('/user/login', {refresh_token: currentTokens.refresh_token})
// Extract tokens and success status from authenticated request
const { tokens, success } = authenticate.data
// If successful, update access_token, id_token, headers and localStorage
if(success) {
currentTokens.access_token = tokens.access_token
currentTokens.id_token = tokens.id_token
const bearer = `Bearer ${tokens.id_token}`
config.headers['Authorization'] = bearer
Object.assign(instance.defaults, {headers: {Authorization: bearer}})
localStorage.setItem('tokens', JSON.stringify(currentTokens))
// Retry original request
return instance(config)
}
} catch (e) {
// Handle any errors
console.log(e)
return
}
} else if(data && data.token_invalid !== undefined && data.token_invalid) {
// Redirect user to ADFS for reauthentication if refresh has expired
location = `${process.env.OAUTH_CLIENT_EP}?client_id=${process.env.AZURE_CLIENT_ID}&redirect_uri=${process.env.REDIRECT_URI}&resource=${process.env.REDIRECT_URI}&response_type=code`
return
} else {
// Log all other errors
return
}
})
export default instance