localstorage do note update JWT Reactjs - javascript

This is the system flow:
I log in a save the user data in localstorage.
I got a component
that read the localStorage to get a user data, like JWT.
The problem is when I do a new login, the localStorage don't update with the new data and so I can't make requisitions that use the localStorage new user data.
I found that if I update manually the page, the localStorage it's udpdated.
In the reactjs I'm using react-router-dom to navigate with the pages.
How can I get new login data to update localStorage?
//login
api.post('users/login', {email, password})//make log in
.then(res => {
localStorage.removeItem('user_info');// I remove the ond data from localStorage
if(res){//If api do the post
let data = JSON.stringify(res.data.data)
localStorage.setItem('user_info', data);//Save new data in localStorage
history.push('/');//Go the homepage
}
}).catch(error => {
this.setState({ noAuth: true })
console.log('error');
});
The component that got the user data in localStorage:
import axios from "axios";
import { isAuthenticated } from '../../components/Util/Auth';
export const token = 'Z31XC52XC4';
// var user_info = JSON.parse(localStorage.getItem('user_info'));
// var auth_token = user_info.auth_token;
// console.log(isAuthenticated);
if (isAuthenticated()) {
var user_info = JSON.parse(localStorage.getItem('user_info'));
var auth_token = user_info.auth_token;
}
const api = axios.create({
// baseURL: 'https://url-from/api/', //PRODUÇÃO
baseURL: 'https://url-from/api/', //DESENVOLVIMENTO
headers: {
'Accept': 'application/json, text/plain, */*',
'Access-Origin': 'D',
'Authorization': `Bearer ${auth_token}`,
'Company-Token': `${token}`
}
});
// console.log(user_info);
api.interceptors.request.use(
config => {
console.log(config.headers);
console.log(user_info);
const newConf = {
...config,
headers: {
...config.headers,
'Authorization': `Bearer ${auth_token}`,
}
}
// return newConf;
},
error => Promise.reject(error)
)
export default api;

When you create an Axios instance you are passing in a "static" value.
'Authorization': `Bearer ${auth_token}`,
if this value doesn't exist, it becomes
'Authorization': `Bearer undefined`,
To fix it, you need to add an interceptor to axios to update the value of that token on EVERY request, not just on instance creation.
api.interceptors.request.use(
config => {
const user_info = JSON.parse(localStorage.getItem('user_info'));
const newConf = {
...config,
headers: {
...config.headers,
'Authorization': `Bearer ${user_info.auth_token}`,
}
}
},
error => Promise.reject(error)
)

I can do this using the tip of my friend JCQuintas
import axios from "axios";
import { isAuthenticated } from '../../components/Util/Auth';
export const token = 'Z31XC52XC4';
const api = axios.create({
// baseURL: 'https://url-from/api/', //PRODUÇÃO
baseURL: 'https://url-from/api/', //DESENVOLVIMENTO
headers: {
'Accept': 'application/json, text/plain, */*',
'Access-Origin': 'D',
// 'Authorization': `Bearer ${auth_token}`,
'Company-Token': `${token}`
}
});
api.interceptors.request.use(function (config) {
console.log(config);
if (isAuthenticated()) {
var user_info = JSON.parse(localStorage.getItem('user_info'));
var auth_token = user_info.auth_token;
}
config.headers.Authorization = `Bearer ${auth_token}`;
return config;
});
export default api;

Related

How can I add an aditional header to global instance of Axios in a custom request?

This is my global Axios
import axios from 'axios';
import { storage } from 'containers/login/utils/local-storage';
const token = storage.getToken();
const axiosInstance = axios.create({
baseURL: process.env.REACT_APP_API_URL,
});
axiosInstance.interceptors.response.use((response) => {
response.config.headers = {
Authorization: `Bearer ${token}`,
};
return response;
}, (error) => Promise.reject(error));
axiosInstance.interceptors.request.use((request) => {
request.headers = {
Authorization: `Bearer ${token}`,
};
return request;
}, (error) => Promise.reject(error));
export default axiosInstance;
In this request I need to add new header: invoiceLimit = `${-invoiceLimit}`
export const updateInvoiceLimit = async (
invoiceLimit: string,
)
: Promise<ReturnDataType> => {
let result: ReturnDataType = {} as ReturnDataType;
try {
axios.defaults.headers.common.invoiceLimit = `${-invoiceLimit}`;
result = await axios.put(`${CREDITS_URL.CREDITS}/invoice/limit`);
return result;
} catch (error) {
SnackBarUtils.error(`${(error as Error).message}. ${result.data.message}`);
}
return result;
};
When I use this: axios.defaults.headers.common.invoiceLimit = `${-invoiceLimit}`;
header adds to the Axios defaults, but then when I call axios.put so this custom header goes away and left only global header from interceptors.
I know it's not best practice, but its customer API and I want not to make another instance of Axios but use one global instance.
I think the problem is here:
axiosInstance.interceptors.request.use((request) => {
request.headers = {
Authorization: `Bearer ${token}`,
};
return request;
}, (error) => Promise.reject(error));
You are overriding all request headers with just this one:
{ Authorization: `Bearer ${token}` }
So try spreading headers before adding the new one like this:
axiosInstance.interceptors.request.use((request) => {
request.headers = {
...request.headers,
Authorization: `Bearer ${token}`,
};
return request;
}, (error) => Promise.reject(error));
Did this solve the problem?
I thought you could just reuse the initial axiosInstance and the headers will be merged when you do:
await axios.put(`${CREDITS_URL.CREDITS}/invoice/limit`,{}, {
headers: {
invoiceLimit: `${-invoiceLimit}`
}
})

Axios - update headers on exported axios.create instance

I have one api.js which exports by default an axios.create() instance:
import axios from 'axios'
import Cookies from 'js-cookie'
const api = axios.create({
baseURL: process.env.VUE_APP_API_URL,
timeout: 10000,
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${Cookies.get('Token')}`,
Organization: Cookies.get('Organization'),
Company: Cookies.get('Company')
}
})
export default api
Then I import this in multiple files like this:
//api/users.js
import api from './api.js'
const methods = {
postUser (params) {
return api.post('/users', params)
},
getUser (id) {
return api.get('/users/' + id)
}
}
export default methods
However there will be some functions that should update the Cookies Organization and Company and I was wondering if is possible to update the default api instance and automatically update it in all imports that use it. I know a simple page refresh would work but I'm building a SPA and I would like to prevent screen to be manually refreshed.
You can add the headers dynamically, that way the cookies will be read on every request.
import axios from 'axios'
import Cookies from 'js-cookie'
const api = axios.create({
baseURL: process.env.VUE_APP_API_URL,
timeout: 10000,
// Static headers
headers: {
'Content-Type': 'application/json',
},
transformRequest: [function (data, headers) {
// You may modify the headers object here
headers['Authorization'] = `Bearer ${Cookies.get('Token')}`
headers['Organization'] = Cookies.get('Organization')
headers['Company'] = Cookies.get('Company')
// Do not change data
return data;
}],
})
export default api
I would suggest to read about interceptor for axios. (https://github.com/axios/axios#interceptors)
A very basic example would be the following.
Lets assume your webservice would return a response http status 401 header.
You'd intercept the response with the following:
// Add a response interceptor
axios.interceptors.response.use(function (response) {
// happy case its 2XX
return response;
}, async (error) => {
if (error.response.status === 401) {
// do some logic to retrieve a new JWT or Cookie.get()
const jwt = Cookies.get('Token');
const config = error.config;
config.headers['Authorization'] = `Bearer ${jwt}`;
}
return await axios.request(config);
});
The next request will then have an authorization header attached to the request header.

How to adapt this axios object with bearer tokens that allows GET, to use POST methods?

I have managed to make this run: How to modify axios instance after exported it in ReactJS?
And it looks like this:
import axios from 'axios';
import constants from '../constants.js';
import Cookies from 'js-cookie';
const API = axios.create({
baseURL: `${constants.urlBackend}`,
timeout: 10000,
headers: {
'Content-Type': 'application/json',
},
});
API.interceptors.request.use(
config => {
var accesstoken = Cookies.get('accesstoken');
if (accesstoken) {
config.headers.Authorization = `Bearer ${accesstoken}`;
} else {
delete API.defaults.headers.common.Authorization;
}
return config;
},
error => Promise.reject(error)
);
export default API;
And this is an example usage
getUserList() {
API.get('/userlist')
.then(response => {
this.setState({
userList: response.data
}, () => {
console.log(this.state.userList)
});
})
}
But now im confused because I dont understand how to use this with a post so I can pass some data to it, similar to this
axios({
method: 'post',
url: constants.urlBackend + "/register",
data: qs.stringify({ email, password }),
headers: {
'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
}
})
But using the above object.
API.post('/user/update/'+this.state.rowId).then(response => {
//some sort of body {email,password}
})
Have you tried
API.post(
'/user/update/' + this.state.rowId, {
email,
password
}).then(response => {})

How can I make an API call that depends on a value which is set by another call?

I have a login function where I am setting a token, that token is saved in a redux store, then, right after the login occurs, I need to make another call to the api which will feed the home screen with data. But in order to make that call, I need the token.
This is the homescreen component where I need to make that call:
// imports
import styles from '../../styles/HomeScreenStyles';
import { passengersDataAction } from './actions/homeScreen';
class HomeScreen extends Component {
static navigationOptions = {
header: null,
};
componentDidMount() {
this.GetPassengersData();
}
GetPassengersData = async () => {
// userToken is coming from the store
const { passengersDataActionHandler, userToken } = this.props;
if (userToken && userToken !== null) {
try {
const response = await fetch(
'http://myAPI/public/api/getPassengers',
{
method: 'POST',
headers: {
Authorization: `Bearer ${userToken}`,
Accept: 'application/json',
'Content-Type': 'application/json',
},
},
);
const responseJson = await response.json();
passengersDataActionHandler(responseJson.success.data);
} // catch ...
}
};
render() {
return <TabView style={styles.container} />;
}
}
// export
By the time GetPassengersData is called userToken is not present yet, so my request goes directly to the catch error callback.
How can I handle it?
EDIT:
The API call I put above is the one where I need the token.
Call to get the logindata:
import { Alert, AsyncStorage } from 'react-native';
import { has } from 'lodash';
import PropTypes from 'prop-types';
const FetchLoginData = async (
username,
password,
navigation,
userTokenActionHandler,
) => {
try {
const response = await fetch(
'http://myAPI/public/api/driverlogin',
{
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({ email: username, password }),
},
);
const responseJson = await response.json();
if (has(responseJson, 'error')) {
Alert.alert('Error', 'Please check your credentials.');
} else {
// HERE I SET THE TOKEN
await AsyncStorage.setItem('userToken', responseJson.success.token);
userTokenActionHandler(responseJson.success.token);
navigation.navigate('App');
}
} catch (error) {
Alert.alert(
'Error',
'There was an error with your request, please try again later.',
);
}
};
FetchLoginData.propTypes = {
navigation: PropTypes.shape({}).isRequired,
userTokenActionHandler: PropTypes.func.isRequired,
};
export default FetchLoginData;
You can put your second call here :
try {
const response = await fetch(
'http://myAPI/public/api/getPassengers',
{
method: 'POST',
headers: {
Authorization: `Bearer ${userToken}`,
Accept: 'application/json',
'Content-Type': 'application/json',
},
},
);
const responseJson = await response.json();
passengersDataActionHandler(responseJson.success.data);
// **put second call here you have token here send it to second api call**
}

localStorage item not updating in axios headers

I am using a JWT Token auth system, and when I login I get the token like this:
axios.post('/login', data)
.then(response => {
localStorage.setItem('token', response.data.token);
});
This works well and the token is saved in localStorage. However, the token is not included in the later requests. The Authorization header is Bearer null.
This is how I set up my global axios object.
window.axios = axios.create({
baseURL: '/api/',
timeout: 10000,
headers: {
'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-TOKEN': document.head.querySelector('meta[name="csrf-token"]').content,
'Authorization': 'Bearer ' + localStorage.getItem('token')
}
});
If I refresh the site, the token is set, and is used properly.
Edit:
I got it to work by removing the Authorization header from the create() method and instead using window.axios.defaults.headers.common['Authorization']. But now the same problem appears with Laravel Echo. I create the instance like this:
window.Echo = new Echo({
broadcaster: 'pusher',
key: 'xxx',
cluster: 'eu',
encrypted: true,
namespace: 'xxx',
auth: {
headers: {
'Authorization': 'Bearer ' + localStorage.getItem('token')
}
}
});
And I update the header like this:
window.setAuthToken = (token) => {
window.axios.defaults.headers.Authorization = 'Bearer ' + token;
window.Echo.options.auth.headers.Authorization = 'Bearer ' + token;
localStorage.setItem('token', token);
}
The axios header is successfully updated, but not Echo.
Use axios interceptors for this purpose. It will run for every request call.
Better to keep axios methods in a separate file and make call to it than using it directly in all components. This way we can replace axios with another library if we want with minimal effort. Here's what I'm doing in my project.
import axios from "axios";
import AuthService from "./auth";
import config from '../config'
const instance = axios.create({
baseURL: config.apiServer.url,
timeout: config.apiServer.timeout
});
instance.interceptors.request.use(
config => {
const token = AuthService.getToken();
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
error => Promise.reject(error)
);
const ApiService = {
get(url) {
return instance.get(url)
.then(res => res)
.catch(reason => Promise.reject(reason));
},
post(url, data) {
return instance.post(url, data)
.then(res => res)
.catch(reason => Promise.reject(reason));
},
awaitAll() {
return axios.all(Array.from(arguments))
.then(axios.spread((...responses) => responses))
.catch(reasons => Promise.reject(reasons));
}
};
export default ApiService;
Now to use it in a component:
ApiService.get(YOUR_GET_URL)
.then(res => {
Console.log(res);
))
.catch(reason => {
console.log(reason);
})
The problem is that your are using localStorage.getItem('token') at page load. When you are setting it in localStorage, you have to update it in axios header.
window.axios = axios.create({
baseURL: '/api/',
timeout: 10000,
headers: {
'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-TOKEN': document.head.querySelector('meta[name="csrf-token"]').content,
'Authorization': 'Bearer ' + localStorage.getItem('token')
}
});
axios.post('/login', data)
.then(response => {
localStorage.setItem('token', response.data.token);
window.axios.defaults.headers.common['Authorization'] = 'Bearer ' + localStorage.getItem('token');
});
I faced the same problem before and I found out that the file that contains my axios config was being loaded at the time of storing the token, so it was accessing it before it is stored.
The solution is, in axios config:
const axiosInstance = axios.create({
baseURL: `${API_BASE_URL}`,
headers: {
Accepted: 'appication/json',
'Content-Type': 'application/json',
},
});
axiosInstance.interceptors.request.use(
(config) => {
const token = localStorage.getItem('token');
if (token) {
config.headers.authorization = token;
}
return config;
},
(error) => Promise.reject(error),
);
export default axiosInstance;
After that, use this instance where you need to make a request.

Categories