I am working on an app that has refresh token functionality. For that, I tried to implement this function after learning about Axios interceptor online. But still, it is not resolved. this how I added this.
I don't know whether it is right or wrong. I just tried implementing refresh token. I had no idea of refresh token before.
Any help would be great.
index.js
axios.interceptors.request.use(
(config) => {
console.log("step-1", config);
const token = localStorageService.getAccessToken();
if (token) {
config.headers["Authorization"] = "Bearer" + token;
}
return config;
},
(error) => {
Promise.reject(error);
}
);
axios.interceptors.response.use(
(response) => {
console.log("step-2", response);
return response;
},
function (error) {
const originalRequest = error.config;
// if (error.response && error.response.status === 401 && !originalRequest._retry) {
// history.push("/");
// return Promise.reject(error);
// }
if (
error.response &&
error.response.status === 401 &&
!originalRequest._retry
) {
originalRequest._retry = true;
const token = UserServices.getOAuth2().createToken(
"refresh_token",
localStorageService.getRefreshToken(),
{ grant_type: "refresh_token" }
);
return token
.refresh()
.then((res) => {
console.log("step3", res);
if (res.status === 201) {
// 1) put token to LocalStorage
localStorageService.setToken(res.data);
// 2) Change Authorization header
axios.defaults.headers.common["Authorization"] =
"Bearer " + localStorageService.getAccessToken();
// 3) return originalRequest object with Axios.
return axios(originalRequest);
}
})
.catch((error) => {
// Dispatch Logout Function here
store.dispatch({
type: LOGIN_ERROR,
});
localStorageService.clearToken();
});
}
}
);
userServices.js
const localStorageService = LocalStorageService.getService();
class UserServices {
getOAuth2 = () => {
var ClientOAuth2 = require("client-oauth2");
const OAuth2 = new ClientOAuth2({
clientId: "development",
clientSecret: "development",
accessTokenUri: "https://api.xxxx.in/oauth/token",
authorizationUri: "https://api.xxxx.in/oauth/authorize",
redirectUri: "https://api.xxxx.in/oauth/callback",
scopes: ["read", "write", "trust"],
});
return OAuth2;
};
logout() {
localStorageService.clearToken();
}
}
I believe you need to call resolve in you error handler and it should fix it:
return token
.refresh()
.then((res) => {
console.log("step3", res);
if (res.status === 201) {
// 1) put token to LocalStorage
localStorageService.setToken(res.data);
// 2) Change Authorization header
axios.defaults.headers.common["Authorization"] =
"Bearer " + localStorageService.getAccessToken();
// 3) return originalRequest object with Axios.
res(axios(originalRequest)); // <- call resolve here
}
})
.catch((error) => {
// Dispatch Logout Function here
store.dispatch({
type: LOGIN_ERROR,
});
localStorageService.clearToken();
});
Related
My question is related to customAxios.interceptors.response.use . My purpose here is; if the token expired and I got a 401 error, make a request again where I got a 401 error and write the new token to the headers. On the other hand, if I get an error except for the 401 error, show me the error.response.data . Do you think this logic is set up correctly? I tried to test but I wasn't sure especially 401 error cases
import axios from "axios";
import { LoginAPI } from "../playwright/tests/login/login.api";
import { test } from "#playwright/test"
import {configEnv} from "../config/config"
test.beforeAll(async () => {
await LoginAPI.API.Signin.run()
});
const customAxios = axios.create({
baseURL: configEnv.apiBaseURL
});
customAxios.interceptors.request.use(
async (config) => {
if (config.headers) {
config.headers['Authorization'] = `Bearer ${LoginAPI.States.token}`;
return config;
}
return config;
},
(error) => {
Promise.reject(error);
}
);
customAxios.interceptors.response.use(
function(response) {
return response;
},
async function(error) {
if (401 === error.response.status) {
await LoginAPI.API.Signin.run()
customAxios.defaults.headers.common['Authorization'] = `Bearer ${LoginAPI.States.token}`
} else {
return Promise.reject(error.response.data);
}
}
);
export default customAxios
I would recommend you to store your token in a localStorage and then replace it after refresh. This way you can set a token in your API class in one place.
import axios from "axios";
export const ApiClient = () => {
// Create a new axios instance
const api = axios.create({
baseURL: "URL",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
});
// Add a request interceptor to add the JWT token to the authorization header
api.interceptors.request.use(
(config) => {
const token = sessionStorage.getItem("jwtToken");
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => Promise.reject(error)
);
// Add a response interceptor to refresh the JWT token if it's expired
api.interceptors.response.use(
(response) => response,
(error) => {
const originalRequest = error.config;
// If the error is a 401 and we have a refresh token, refresh the JWT token
if (
error.response.status === 401 &&
sessionStorage.getItem("refreshToken")
) {
const refreshToken = sessionStorage.getItem("refreshToken");
let data = JSON.stringify({
refresh_token: refreshToken,
});
post("/refreshToken", data)
.then((response) => {
sessionStorage.setItem("jwtToken", response.token);
sessionStorage.setItem("refreshToken", response.refresh_token);
// Re-run the original request that was intercepted
originalRequest.headers.Authorization = `Bearer ${response.token}`;
api(originalRequest)
.then((response) => {
return response.data;
})
.catch((error) => {
console.log(error);
});
// return api(originalRequest)
})
.catch((err) => {
// If there is an error refreshing the token, log out the user
console.log(err);
});
}
// Return the original error if we can't handle it
return Promise.reject(error);
}
);
const login = (email, password) => {
return api
.post("/authentication_token", { email, password })
.then(({ data }) => {
// Store the JWT and refresh tokens in session storage
sessionStorage.setItem("jwtToken", data.token);
sessionStorage.setItem("refreshToken", data.refresh_token);
})
.catch((err) => {
// Return the error if the request fails
return err;
});
};
const get = (path) => {
return api.get(path).then((response) => response.data);
};
const post = (path, data) => {
return api.post(path, data).then((response) => response.data);
};
const put = (path, data) => {
return api.put(path, data).then((response) => response.data);
};
const del = (path) => {
return api.delete(path).then((response) => response);
};
return {
login,
get,
post,
put,
del,
};
};
Best,
Chris
This is my axios-hoook.js and I am using axios-hooks package.
import useAxios from 'axios-hooks';
import axios from 'axios';
import LocalStorageService from './services/local-storage.service';
import refreshToken from './refresh-token';
axios.defaults.baseURL = 'http://localhost:3000/api/v1';
axios.defaults.transformResponse = [
(responseData) => {
const { data, error } = JSON.parse(responseData);
return error || data;
},
];
// request interceptor to add token to request headers
axios.interceptors.request.use(
async (config) => {
const token = LocalStorageService.getAccessToken();
if (token) {
config.headers = {
authorization: token,
};
}
return config;
},
(error) => Promise.reject(error)
);
// response interceptor intercepting 401 responses, refreshing token and retrying the request
axios.interceptors.response.use(
(response) => response,
(error) => {
const { config } = error;
if (error.response?.status === 401 && !config._retry) {
config._retry = true;
refreshToken(LocalStorageService.getRefreshToken())
.then((res) => {
const { accessToken } = res.data.data;
LocalStorageService.setAccessToken(accessToken);
return axios(config);
})
.catch((err) => {
if (err.response.status === 401) {
LocalStorageService.setUser(null);
window.location.href = '/login';
}
return Promise.reject(err);
});
}
return Promise.reject(error);
}
);
export default useAxios;
This is the Course.jsx where it is being used.
const Course = () => {
const [{ data: courses = [] }, refetchCourse] = axiosHook(ApiConfig.COURSE.GET_COURSES.url);
return (
<Datatable
entity={entity}
columns={courseColumns}
rows={courses}
deleteRow={handleDeactivate}
viewRow={handleView}
/>
)
}
Image
In the axios-hooks docs there's a link to a working example to implement a refresh token feature. It is running in CodeSandbox at this link https://codesandbox.io/s/axios-hooks-authentication-zyeyh.
Compare that with your example and you'll find the reason why yours doesn't work.
There was an error in my code. I was not returning the promise.
axios.interceptors.response.use(
(response) => response,
(error) => {
const { config } = error;
if (error.response?.status === 401 && !config._retry) {
config._retry = true;
return refreshToken(LocalStorageService.getRefreshToken()) // this line
.then((res) => {
const { accessToken } = res.data.data;
LocalStorageService.setAccessToken(accessToken);
return axios(config);
})
.catch((err) => {
if (err.response.status === 401) {
LocalStorageService.setUser(null);
window.location.href = '/login';
}
return Promise.reject(err);
});
}
return Promise.reject(error);
}
);
I am recreating the issue as I am not sure if that's a bug and a previous issue created for this just disappeared =/
Description
During an upgrade from react-admin v2 to v3.3.0, I encounter issue to get redirected to /login after rewriting the authProvider
react-admin documentation | github
My authProvider.js contains the following methods:
export default function createAuthProvider(urls, client, options) {
return {
login: (params) => {
return fetchLoginBatch(params, urls, client, options);
},
logout: (params) => params.jwt ? fetchLogout(makeRequestLogout(urls.logout, params.jwt), options) : Promise.resolve(),
checkError: (error) => {
const { status } = error;
if (status === 401 || status === 403) {
return Promise.reject();
}
return Promise.resolve();
},
checkAuth: (params) => params.jwt ? Promise.resolve() : Promise.reject(),
getPermissions: (params) => params.jwt ? Promise.resolve(params.jwt.authorities) : Promise.resolve(),
refreshJwt: (params) => params.jwt ? fetchRefreshJwt(makeRefreshJwtRequest(client.accessTokenUri, {
grant_type: 'refresh_token',
refresh_token: params.jwt.refresh_token,
}, client), options) : Promise.resolve()
};
}
It is as described in documentation and example
Expected
I expect to be redirected to /login.
Result
Instead, I stay on the page, checkAuth is well called and the jwt is null,
Possible fix
It is offered to change the redirect using an argument to rejected promise:
checkAuth: () => localStorage.getItem('token')
? Promise.resolve()
: Promise.reject({ redirectTo: '/no-access' }),
But adding Promise.reject({ redirectTo: '/login' }) doesn't help even if the code run.
I have tried to add some logging in ra-core/lib/sideEffect/auth.js:
console.log('auth');
exports.handleCheck = function (authProvider) {
console.log('handleCheck', authProvider);
return function (action) {
console.log('action', action);
var payload, meta, error_1, redirectTo, errorMessage;
console.log('redirectTo', redirectTo, 'meta', meta);
handleCheck is called but never action, it seems that the saga is ignored somehow.
Question
How should client side handle permissions and checkAuth rejection params ?
What should I check next to see why the redirection is failing?
How does the ra-core code follow?
Could you kindly scrutinize this line?
// authProvider.js
// checking if request has a JWT (this might be a typo!)
- checkAuth: (params) => params.jwt ? Promise.resolve() : Promise.resolve(),
// If not, we should reject thus triggering a redirect.
+ checkAuth: (params) => params.jwt ? Promise.resolve() : Promise.reject(),
Let me know how it works out.
Here is an example of authProvider, it works with both React-Admin 2 and React-Admin 3.3.1
Using:
<Admin authProvider={authProvider(loginUrl, logoutUrl)} ...>
import storage from './storage'
import {
AUTH_LOGIN,
AUTH_LOGOUT,
AUTH_ERROR,
AUTH_CHECK,
AUTH_GET_PERMISSIONS
} from 'react-admin'
import {
LB_TOKEN,
getTokenId
} from './token'
export const authProvider = (loginApiUrl, logoutApiUrl, noAccessPage = '/login') => {
return (type, params) => {
if (type === AUTH_LOGIN) {
const request = new Request(loginApiUrl, {
method: 'POST',
body: JSON.stringify(params),
headers: new Headers({ 'Content-Type': 'application/json' }),
})
return fetch(request)
.then(response => {
if (response.status < 200 || response.status >= 300) {
throw new Error(response.statusText)
}
return response.json()
})
.then(({ ttl, ...data }) => {
storage.save(LB_TOKEN, data, ttl)
return Promise.resolve(data)
})
}
if (type === AUTH_LOGOUT) {
const token = getTokenId()
if (token) {
storage.remove(LB_TOKEN)
if (logoutApiUrl) {
const request = new Request(`${logoutApiUrl}?access_token=${token}`, {
method: 'POST',
headers: new Headers({'Content-Type': 'application/json'}),
})
return fetch(request)
.then(response => {
if (response.status !== 204) {
console.error('authProvider - Logout, status:', response)
}
return Promise.resolve()
})
}
}
return Promise.resolve()
}
if (type === AUTH_ERROR) {
const { status } = params
if (status === 401 || status === 403) {
storage.remove(LB_TOKEN)
return Promise.reject()
}
return Promise.resolve()
}
if (type === AUTH_CHECK) {
const token = storage.load(LB_TOKEN)
if (token && token.id) {
return Promise.resolve()
} else {
storage.remove(LB_TOKEN)
return Promise.reject({ redirectTo: noAccessPage })
}
}
if (type === AUTH_GET_PERMISSIONS) {
const token = storage.load(LB_TOKEN)
if (token && token.user && token.user.roleId) {
return Promise.resolve(token.user.roleId)
} else {
console.warn('Unknown user rights:', token)
storage.remove(LB_TOKEN)
return Promise.reject({ redirectTo: noAccessPage })
}
}
return Promise.reject(`authProvider - Unknown method, type: ${type}, params: ${params}`)
}
}
I'm using the library axios in my react app.
I'm having a problem with the interceptor.
My question is let say I have three requests happening concurrently and I don't have the token, the interceptor calling the getUserRandomToken three time, I want the interceptor will wait until I'm getting the token from the first request and then continue to the others.
P.S. the token he is with an expiration date so I also checking for it and if the expiration date is not valid I need to create a new token.
This is the interceptor:
axios.interceptors.request.use(
config => {
/*I'm getting the token from the local storage
If there is any add it to the header for each request*/
if (tokenExist()) {
config.headers.common["token"] = "...";
return config;
}
/*If there is no token i need to generate it
every time create a random token, this is a axios get request*/
getUserRandomToken()
.then(res => {
/*add the token to the header*/
config.headers.common["token"] = res;
return config;
})
.catch(err => {
console.log(err);
});
},
function(error) {
// Do something with request error
return Promise.reject(error);
}
);
How about singleton object that will handle the token generations? something similar to this:
const tokenGenerator ={
getTokenPromise: null,
token: null,
getToken(){
if (!this.getTokenPromise){
this.getTokenPromise = new Promise(resolve=>{
/*supposed to be a http request*/
if (!this.token){
setTimeout(()=>{
this.token = 'generated';
resolve(this.token);
},0)
}else{
resolve(this.token);
}
})
}
return this.getTokenPromise;
}
you can reference this same object from the interceptors.
see example: JS FIddle
reference: reference
You can return a Promise from interceptor callback to "wait" until promise fullfiles (this will fit your case). Check out this example:
function axiosCall () {
return new Promise((resolve, reject) => {
Axios.post(URL, {apiKey}).then((response) => {
resolve(response.data.message);
}).catch((error) => {
reject(error);
});
});
}
instance.interceptors.request.use((config) => {
return axiosCall().then((tokenResponse) => {
setWebCreds(tokenResponse);
config.headers.Authorization = `Bearer ${tokenResponse}`;
return Promise.resolve(config)
}).catch(error => {
// decide what to do if you can't get your token
})
}, (error) => {
return Promise.reject(error);
});
More details here: https://github.com/axios/axios/issues/754
Following code doing certain tasks:
Update Token on 401
Make a queue of failed requests while the token is refreshing.
Restore the original request after token refreshing.
Once the peculiar request is given 200, remove it from the queue.
Config.js
import axios from 'axios';
import { AsyncStorage } from 'react-native';
import { stateFunctions } from '../../src/sharedcomponent/static';
const APIKit = axios.create({
baseURL: '',
timeout: 10000,
withCredentials: true,
});
const requestArray = [];
// Interceptor for Request
export const setClientToken = token => {
APIKit.interceptors.request.use(
async config => {
console.log('Interceptor calling');
let userToken = await AsyncStorage.getItem('userToken');
userToken = JSON.parse(userToken);
config.headers = {
'Authorization': `Bearer ${userToken}`,
'Accept': 'application/json',
"Content-Type": "application/json",
"Cache-Control": "no-cache",
}
// console.log('caling ' , config)
return config;
},
error => {
Promise.reject(error)
});
};
// Interceptor for Response
APIKit.interceptors.response.use(
function (response) {
if (requestArray.length != 0) {
requestArray.forEach(function (x, i) {
if (response.config.url == x.url) {
requestArray.splice(i, 1);
}
});
}
return response;
},
function (error) {
const originalRequest = error.config;
requestArray.push(originalRequest);
let reqData = "username=" + number + "&password=" + pin + "&grant_type=password" + "&AppType=2" + "&FcmToken=null";
// console.log('error ' , error);
if (error.message === "Request failed with status code 401" || error.statuscode === 401) {
if (!originalRequest._retry) {
originalRequest._retry = true;
return axios({
method: 'post',
url: '/api/login',
data: reqData,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Cache-Control": "no-cache",
}
})
.then(res => {
let response = res.data;
console.log('successfull Login', response)
if (res.data.StatusCode == 200) {
AsyncStorage.setItem('userToken', JSON.stringify(response.access_token));
stateFunctions.UserId = response.UserId;
stateFunctions.CustomerContactID = response.CustomerContactID;
let obj = {
access_token: response.access_token,
token_type: response.token_type,
expires_in: response.expires_in,
UserId: response.UserId,
CustomerContactID: response.CustomerContactID,
Mobile: response.Mobile,
StatusCode: response.StatusCode
}
AsyncStorage.setItem('logindetail', JSON.stringify(obj));
if (requestArray.length != 0) {
requestArray.forEach(x => {
try {
console.log(x, "request Url");
x.headers.Authorization = `Bearer ${response.access_token}`;
x.headers["Content-Type"] = "application/x-www-form-urlencoded";
APIKit.defaults.headers.common["Authorization"] = `Bearer${response.access_token}`;
APIKit(x)
} catch (e) {
console.log(e)
}
});
}
return APIKit(originalRequest);
}
})
.catch(err => {
console.log(err);
});
}
}
return Promise.reject(error);
}
);
export default APIKit;
Home.js
gettingToken = async () => {
let userToken = await AsyncStorage.getItem('userToken');
userToken = JSON.parse(userToken);
await setClientToken(userToken);
}
I'm using Nuxt-axios module with the proxy.
For Error handling, I have common code in
Plugins/axios.js
export default function({ $axios, __isRetryRequest, store, app, redirect , payload , next}) {
$axios.onRequest(config => {
if (app.$cookies.get('at') && app.$cookies.get('rt') && config.url != '/post_login/') {
config.headers.common['Authorization'] = `Bearer ${app.$cookies.get('at')}`;
}
});
$axios.onResponseError(err => {
const code = parseInt(err.response && err.response.status)
let originalRequest = err.config;
if (code === 401) {
originalRequest.__isRetryRequest = true;
store
.dispatch('LOGIN', { grant_type: 'refresh_token', refresh_token: app.$cookies.get('rt')})
.then(res => {
originalRequest.headers['Authorization'] = 'Bearer ' + app.$cookies.get('at');
return app.$axios(originalRequest);
})
.catch(error => {
console.log(error);
});
}
// code for 422 error
if (code == 422) {
throw err.response;
}
});
}
On my page folder index page
Pages/index.vue
<template>
<section>Component data</section>
</template>
<script type="text/javascript">
export default {
async asyncData({ route, store }) {
await store.dispatch('GET_BANNERS');
}
}
</script>
All the API calls are in a stroes/actions.js file.
Now the question is when I refresh the page index.vue first API request will hit and get the response if successful. But now if on first request( 'GET_BANNERS' ) from asyncData and it gets 401 error unauthorized then I'm getting below error
Error: Request failed with status code 401
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
how can I resolve this?
few more questions:
1) When I'm writing common error code in axios, original request on which I have received 401 how can I set data to store again(which we normally do from actions file)?
2) can anyone help with best practice to attach authorization headers and error handle for 400,401,422, etc..
$axios.onResponseError(err => {
const code = parseInt(err.response && err.response.status);
let originalRequest = err.config;
if (code == 401) {
originalRequest.__isRetryRequest = true;
let token = app.$cookies.get('rt');
return new Promise((resolve, reject) => {
let req = $axios
.post(`/login`, { grant_type: 'refresh_token', refresh_token: token })
.then(response => {
if (response.status == 200) {
app.$cookies.set('access', response.data.access_token);
app.$cookies.set('refresh', response.data.refresh_token);
originalRequest.headers['Authorization'] = `Bearer ${
response.data.access_token
}`;
}
resolve(response);
}).catch(e => {
reject("some message");
})
})
.then(res => {
return $axios(originalRequest);
}).catch(e => {
app.router.push('/login');
});
}
});
#canet-robern hope this will solve your prob!!
The error ERR_HTTP_HEADERS_SENT means that you have a bug in your server-side code - hence the error from this bug comes before the HTTP headers.
To handle 4xx errors and retry the Axios request - follow this example:
Vue.prototype.$axios = axios.create(
{
headers:
{
'Content-Type': 'application/json',
},
baseURL: process.env.API_URL
}
);
Vue.prototype.$axios.interceptors.request.use(
config =>
{
events.$emit('show_spin');
let token = getTokenID();
if(token && token.length) config.headers['Authorization'] = token;
return config;
},
error =>
{
events.$emit('hide_spin');
if (error.status === 401) VueRouter.push('/login');
else throw error;
}
);
Vue.prototype.$axios.interceptors.response.use(
response =>
{
events.$emit('hide_spin');
return response;
},
error =>
{
events.$emit('hide_spin');
return new Promise(function(resolve,reject)
{
if (error.config && error.response && error.response.status === 401 && !error.config.__isRetry)
{
myVue.refreshToken(function()
{
error.config.__isRetry = true;
error.config.headers['Authorization'] = getTokenID();
myVue.$axios(error.config).then(resolve,reject);
},function(flag) // true = invalid session, false = something else
{
if(process.env.NODE_ENV === 'development') console.log('Could not refresh token');
if(getUserID()) myVue.showFailed('Could not refresh the Authorization Token');
reject(flag);
});
}
else throw error;
});
}
);