I have an issue with refresh tokens in react and I am using axios interceptors for calling refresh token I am recieving refresh token from flask APIs and the timer of refresh token is 30sec
This is the frontpage of login:
This is the login page;
After login I am recieving this data from the api:
data reacieved: After 30sec I am recieving this error and I am not able to call refresh tokens again for getting data from api
This is my code:`
This is the code where I am creating axios instance and interceptors for req and res:
import axios from 'axios';
const instance = axios.create({
baseURL: "http://192.168.18.63:5000",
headers: { "Content-Type": "application/json" },
});
instance.interceptors.request.use(config => {
const accessToken = localStorage.getItem('access_token');
if (accessToken) {
config.headers.Authorization = `Bearer ${accessToken}`;
}
return config;
});
instance.interceptors.response.use(
response => {
return response;
},
error => {
// If the access token is expired, try to refresh it
if (error.response.data.status === 403 && error.response.data.msg === 'Access token expired') {
const refreshToken = localStorage.getItem('refresh_token');
// Send a request to the server to refresh the access token
return instance
.post('/AdminRefreshToken', {
refresh_token: refreshToken,
})
.then(response => {
// Save the new access token
localStorage.setItem('access_token', response.data.access_token);
// Retry the original request
const config = error.config;
config.headers.Authorization = `Bearer ${response.data.access_token}`;
return instance(config);
});
}
return Promise.reject(error);
}
);
export default instance;`
This is the code where I am fetching the data from axios instance:
import React, { useState, useEffect } from "react";
import Logout from "./logout";
import api from "./Services/Api";
function MyComponent() {
const [data, setData] = useState("");
`your text`
useEffect(() => {
api
.get("/AdminDetails")
.then((response) => {
console.log(response);
setData(response.data.data);
})
.catch((error) => {
console.log(error);
});
}, []);
return <>
<div>
<h4>email: {data.email}</h4>
<h4>first Name: {data.firstname}</h4>
<h4>last Name: {data.lastname}</h4>
<h4>user Name: {data.username}</h4>
<Logout/>
</div>
</>;
}
export default MyComponent;
I am building a jwt token refresh logic (refresh the authentication token when it expires) with axios interceptors. The refresh part works well : axios intercepts the error, refreshes the token, and retries the request (and successfully gets an answer from the server).
However, the page that made the request that failed because of the expired token still catches the error. I feel like axios still returns the error to the function that made the call instead of just returning the retried request, but idk how.
Here is the code in my axios.js file :
import { boot } from "quasar/wrappers";
import axios from "axios";
import * as storage from "../helpers/storage";
import store from "../store/index.js";
import router from "../router/index.js";
const api = axios.create({
baseURL: process.env.API_URL,
crossdomain: true,
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
});
api.interceptors.request.use(
function (config) {
if (config.url !== "/register") {
const accessToken = storage.getAccessToken();
if (accessToken) {
config.headers.Authorization = "Bearer " + accessToken;
}
}
return config;
},
function (error) {
// Do something with request error
return Promise.reject(error);
}
);
api.interceptors.response.use(
function (response) {
// Any status code that lie within the range of 2xx cause this function to trigger
// Do something with response data
return response;
},
function (error) {
// Any status codes that falls outside the range of 2xx cause this function to trigger
// Do something with response error
if (error.response.data.message === "Expired JWT Token") {
const originalRequest = error.config;
api
.post("/token/refresh", { refresh_token: storage.getRefreshToken() })
.then(({ data }) => {
if (data !== undefined) {
storage.setTokens(data.token, data.refresh_token);
}
originalRequest.headers = { Authorization: `Bearer ${data.token}` };
return new Promise(() => {
axios.request(originalRequest).then((response) => {
return response;
});
});
})
.catch((error) => {
console.error(error);
});
} else if (error.response.data.message === "Invalid JWT Token") {
console.log("error");
store()
.dispatch("auth/logout")
.then(() => {
router().push({
name: "register-login",
query: { error: "invalid_token" },
});
router().go(0);
store().dispatch("setLoading", false);
});
} else {
return Promise.reject(error);
}
}
);
export default boot(({ app }) => {
// for use inside Vue files (Options API) through this.$axios and this.$api
app.config.globalProperties.$axios = axios;
// ^ ^ ^ this will allow you to use this.$axios (for Vue Options API form)
// so you won't necessarily have to import axios in each vue file
app.config.globalProperties.$api = api;
// ^ ^ ^ this will allow you to use this.$api (for Vue Options API form)
// so you can easily perform requests against your app's API
});
export { axios, api };
And here is an example of a request I do :
export function sendTags(context, payload) {
return new Promise((resolve, reject) => {
api
.post("/spot/addTags", payload)
.then(({ data }) => {
resolve(data);
})
.catch((error) => {
reject(error.response.data);
});
});
Any idea of what could be going wrong ?
You didn't return a success result in the error function of response interceptor.
api.interceptors.response.use(
function (response) {
return response;
},
function (error) {
if (error.response.data.message === "Expired JWT Token") {
// You didn't return here!
// change to:
return api.post()
.than(() => {
// resolve the final result here
return axios.request(originalRequest)
})
}
}
)
Axios interceptors works really well for http://127.0.0.1:8000 local API calls. Here is the working code.
import axios from 'axios';
const http = axios.create({
baseURL: 'http://127.0.0.1:8000/api/',
Headers: {},
});
try {
http.interceptors.request.use(
(config) => {
let data = JSON.parse(localStorage.getItem('cyber-minds'));
if (data && data.user_status.token) {
config.headers['Authorization'] = 'Token ' + data.user_status.token;
}
return config;
},
(error) => {
return Promise.reject(error);
}
);
} catch (error) {
console.log(error);
}
export default http;
But after I deploy http://127.0.0.1:8000 to https://mysite-backend.herokuapp.com and replace my baseURL with https://mysite-backend.herokuapp.com it returns invalid token. here is the code which returns invalid token.
import axios from 'axios';
const http = axios.create({
baseURL: 'https://cyberminds-backend.herokuapp.com/api/',
Headers: {},
});
try {
http.interceptors.request.use(
(config) => {
let data = JSON.parse(localStorage.getItem('cyber-minds'));
if (data && data.user_status.token) {
config.headers['Authorization'] = 'Token ' + data.user_status.token;
}
return config;
},
(error) => {
return Promise.reject(error);
}
);
} catch (error) {
console.log(error);
}
export default http;
Here is local storage information.
{token: "e3746603ad6c8788b9936118f1fc36289bb20a8d", user: {id: 2,…},…}
assetRisk: "Low"
cid: 1
cpe: "cpe:2.3:a:oracle:peoplesoft_enterprise:8.22.14"
id: 2
name: ""
pid: 2
pr: "Windows"
token: "e3746603ad6c8788b9936118f1fc36289bb20a8d"
user: {id: 2,…}
user_status: {loggedIn: true, token: "e3746603ad6c8788b9936118f1fc36289bb20a8d"}
vendor: "Oracle"
The authentication is working very well. Authorization returns invalid token how can i resolve this issue?
I have a react/redux application that fetches a token from an api server. After the user authenticates I'd like to make all axios requests have that token as an Authorization header without having to manually attach it to every request in the action. I'm fairly new to react/redux and am not sure on the best approach and am not finding any quality hits on google.
Here is my redux setup:
// actions.js
import axios from 'axios';
export function loginUser(props) {
const url = `https://api.mydomain.com/login/`;
const { email, password } = props;
const request = axios.post(url, { email, password });
return {
type: LOGIN_USER,
payload: request
};
}
export function fetchPages() {
/* here is where I'd like the header to be attached automatically if the user
has logged in */
const request = axios.get(PAGES_URL);
return {
type: FETCH_PAGES,
payload: request
};
}
// reducers.js
const initialState = {
isAuthenticated: false,
token: null
};
export default (state = initialState, action) => {
switch(action.type) {
case LOGIN_USER:
// here is where I believe I should be attaching the header to all axios requests.
return {
token: action.payload.data.key,
isAuthenticated: true
};
case LOGOUT_USER:
// i would remove the header from all axios requests here.
return initialState;
default:
return state;
}
}
My token is stored in redux store under state.session.token.
I'm a bit lost on how to proceed. I've tried making an axios instance in a file in my root directory and update/import that instead of from node_modules but it's not attaching the header when the state changes. Any feedback/ideas are much appreciated, thanks.
There are multiple ways to achieve this. Here, I have explained the two most common approaches.
1. You can use axios interceptors to intercept any requests and add authorization headers.
// Add a request interceptor
axios.interceptors.request.use(function (config) {
const token = store.getState().session.token;
config.headers.Authorization = token;
return config;
});
2. From the documentation of axios you can see there is a mechanism available which allows you to set default header which will be sent with every request you make.
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
So in your case:
axios.defaults.headers.common['Authorization'] = store.getState().session.token;
If you want, you can create a self-executable function which will set authorization header itself when the token is present in the store.
(function() {
String token = store.getState().session.token;
if (token) {
axios.defaults.headers.common['Authorization'] = token;
} else {
axios.defaults.headers.common['Authorization'] = null;
/*if setting null does not remove `Authorization` header then try
delete axios.defaults.headers.common['Authorization'];
*/
}
})();
Now you no longer need to attach token manually to every request. You can place the above function in the file which is guaranteed to be executed every time (e.g: File which contains the routes).
Create instance of axios:
// Default config options
const defaultOptions = {
baseURL: <CHANGE-TO-URL>,
headers: {
'Content-Type': 'application/json',
},
};
// Create instance
let instance = axios.create(defaultOptions);
// Set the AUTH token for any request
instance.interceptors.request.use(function (config) {
const token = localStorage.getItem('token');
config.headers.Authorization = token ? `Bearer ${token}` : '';
return config;
});
Then for any request the token will be select from localStorage and will be added to the request headers.
I'm using the same instance all over the app with this code:
import axios from 'axios';
const fetchClient = () => {
const defaultOptions = {
baseURL: process.env.REACT_APP_API_PATH,
method: 'get',
headers: {
'Content-Type': 'application/json',
},
};
// Create instance
let instance = axios.create(defaultOptions);
// Set the AUTH token for any request
instance.interceptors.request.use(function (config) {
const token = localStorage.getItem('token');
config.headers.Authorization = token ? `Bearer ${token}` : '';
return config;
});
return instance;
};
export default fetchClient();
The best solution to me is to create a client service that you'll instantiate with your token an use it to wrap axios.
import axios from 'axios';
const client = (token = null) => {
const defaultOptions = {
headers: {
Authorization: token ? `Token ${token}` : '',
},
};
return {
get: (url, options = {}) => axios.get(url, { ...defaultOptions, ...options }),
post: (url, data, options = {}) => axios.post(url, data, { ...defaultOptions, ...options }),
put: (url, data, options = {}) => axios.put(url, data, { ...defaultOptions, ...options }),
delete: (url, options = {}) => axios.delete(url, { ...defaultOptions, ...options }),
};
};
const request = client('MY SECRET TOKEN');
request.get(PAGES_URL);
In this client, you can also retrieve the token from the localStorage / cookie, as you want.
Similarly, we have a function to set or delete the token from calls like this:
import axios from 'axios';
export default function setAuthToken(token) {
axios.defaults.headers.common['Authorization'] = '';
delete axios.defaults.headers.common['Authorization'];
if (token) {
axios.defaults.headers.common['Authorization'] = `${token}`;
}
}
We always clean the existing token at initialization, then establish the received one.
The point is to set the token on the interceptors for each request
import axios from "axios";
const httpClient = axios.create({
baseURL: "http://youradress",
// baseURL: process.env.APP_API_BASE_URL,
});
httpClient.interceptors.request.use(function (config) {
const token = localStorage.getItem('token');
config.headers.Authorization = token ? `Bearer ${token}` : '';
return config;
});
If you want to call other api routes in the future and keep your token in the store then try using redux middleware.
The middleware could listen for the an api action and dispatch api requests through axios accordingly.
Here is a very basic example:
actions/api.js
export const CALL_API = 'CALL_API';
function onSuccess(payload) {
return {
type: 'SUCCESS',
payload
};
}
function onError(payload) {
return {
type: 'ERROR',
payload,
error: true
};
}
export function apiLogin(credentials) {
return {
onSuccess,
onError,
type: CALL_API,
params: { ...credentials },
method: 'post',
url: 'login'
};
}
middleware/api.js
import axios from 'axios';
import { CALL_API } from '../actions/api';
export default ({ getState, dispatch }) => next => async action => {
// Ignore anything that's not calling the api
if (action.type !== CALL_API) {
return next(action);
}
// Grab the token from state
const { token } = getState().session;
// Format the request and attach the token.
const { method, onSuccess, onError, params, url } = action;
const defaultOptions = {
headers: {
Authorization: token ? `Token ${token}` : '',
}
};
const options = {
...defaultOptions,
...params
};
try {
const response = await axios[method](url, options);
dispatch(onSuccess(response.data));
} catch (error) {
dispatch(onError(error.data));
}
return next(action);
};
Sometimes you get a case where some of the requests made with axios are pointed to endpoints that do not accept authorization headers. Thus, alternative way to set authorization header only on allowed domain is as in the example below. Place the following function in any file that gets executed each time React application runs such as in routes file.
export default () => {
axios.interceptors.request.use(function (requestConfig) {
if (requestConfig.url.indexOf(<ALLOWED_DOMAIN>) > -1) {
const token = localStorage.token;
requestConfig.headers['Authorization'] = `Bearer ${token}`;
}
return requestConfig;
}, function (error) {
return Promise.reject(error);
});
}
Try to make new instance like i did below
var common_axios = axios.create({
baseURL: 'https://sample.com'
});
// Set default headers to common_axios ( as Instance )
common_axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// Check your Header
console.log(common_axios.defaults.headers);
How to Use it
common_axios.get(url).......
common_axios.post(url).......
export const authHandler = (config) => {
const authRegex = /^\/apiregex/;
if (!authRegex.test(config.url)) {
return store.fetchToken().then((token) => {
Object.assign(config.headers.common, { Authorization: `Bearer ${token}` });
return Promise.resolve(config);
});
}
return Promise.resolve(config);
};
axios.interceptors.request.use(authHandler);
Ran into some gotchas when trying to implement something similar and based on these answers this is what I came up with. The problems I was experiencing were:
If using axios for the request to get a token in your store, you need to detect the path before adding the header. If you don't, it will try to add the header to that call as well and get into a circular path issue. The inverse of adding regex to detect the other calls would also work
If the store is returning a promise, you need to return the call to the store to resolve the promise in the authHandler function. Async/Await functionality would make this easier/more obvious
If the call for the auth token fails or is the call to get the token, you still want to resolve a promise with the config
I'm running Vue.js and axios and are trying to make a generic API object like the following:
import router from './router'
import auth from './auth'
const axios = require('axios')
export const API = axios.create({
baseURL: `https://my-api.com/`,
headers: {
Authorization: auth.getToken()
}
})
API.interceptors.response.use(null, function (error) {
if (error.response.status === 401) {
console.log('Failed to login')
router.push('/Login')
}
return Promise.reject(error)
})
I'm trying to have the users redirected to the Login screen in my single page app, whenever a 401 error code is received.
But I'm not getting redirected, and no error occurs in my Developer Tools in Chrome. I do get the console.log with Failed to login.
I have detected a similar situation. I haved fixed with this code:
import router from 'router'
import store from 'store'
...
...
axios.interceptors.response.use(function (response) {
return response
}, function (error) {
console.log(error.response.data)
if (error.response.status === 401) {
store.dispatch('logout')
router.push('/login')
}
return Promise.reject(error)
})
You can do something like follow:
axios.post("quote", params)
.catch(function(error) {
if (error.response && error.response.status === 401) {
window.location.href = "logon";
} else {
// Handle error however you want
}
});
Source: https://github.com/axios/axios/issues/396#issuecomment-395592900
you Can use below code and add httpClient.js file to your project:
import axios from 'axios';
import {
authHeader
}
from '../helper'
const baseUrl = 'http://localhost:8811/api/';//local-test
const Api_Path = `${baseUrl}/`;
const httpClient = axios.create({
baseURL: Api_Path,
headers: {
//Authorization: 'Bearer {token}',
//timeout: 1000, // indicates, 1000ms ie. 1 second
"Content-Type": "application/json",
}
})
const authInterceptor = (config) => {
config.headers['Authorization'] = authHeader();
return config;
}
const errorInterceptor = error => {
// check if it's a server error
if (!error.response) {
//notify.warn('Network/Server error');
console.error('**Network/Server error');
console.log(error.response);
return Promise.reject(error);
}
// all the other error responses
switch (error.response.status) {
case 400:
console.error(error.response.status, error.message);
//notify.warn('Nothing to display', 'Data Not Found');
break;
case 401: // authentication error, logout the user
//notify.warn('Please login again', 'Session Expired');
console.error(error.response.status, error.message);
localStorage.removeItem('token');
localStorage.removeItem('user');
//router.push('/auth');
break;
default:
console.error(error.response.status, error.message);
//notify.error('Server Error');
}
return Promise.reject(error);
}
httpClient.interceptors.request.use(authInterceptor);
httpClient.interceptors.response.use(responseInterceptor, errorInterceptor);
export default httpClient;