Reputation: 21
I have problem with setting authorization header in the axios GET request. I've done a lot of research, but didn't find solution. Also I checked the CORS settings and it supposed to be ok and the request is working from postman or advance rest client, so I don't believe thats the problem on the server side.
My function with axios request
export function getUserInfo (userId) {
return function (dispatch) {
axios.get(`${ROOT_URL}/user/${userId}`, helperMethods.authorizedHeader())
.then(response => {
dispatch({type: USER_INFO, payload: response.data.message});
})
.catch(error => {
console.log('something went wrong: ', error);
});
};
}
Helper method (which is returning valid object, I debugged it)
export function authorizedHeader () {
let token = sessionStorage.getItem(TOKEN);
if (!token) {
token = localStorage.getItem(TOKEN);
}
return {
headers: {
'Accept': 'application/json',
'Authorization': `${token}`
}
};
}
And CORS settings:
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
So if you have any advice please share it with me.
Thank you
Upvotes: 1
Views: 1563
Reputation: 21
Finally, I found the problem. Problem was with my CORS configuration on the server side. When request is triggered it firstly goes to the spring CORS filter, which is rejecting request, and it's never triggering my CORS filter. So I have to set order of triggering, something like that:
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(-110);
And here is whole updated CORS config:
@Bean
public FilterRegistrationBean platformCorsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration configAutenticacao = new CorsConfiguration();
configAutenticacao.setAllowCredentials(true);
configAutenticacao.addAllowedOrigin("*");
configAutenticacao.addAllowedHeader("Authorization");
configAutenticacao.addAllowedHeader("Content-Type");
configAutenticacao.addAllowedHeader("Accept");
configAutenticacao.addAllowedMethod("POST");
configAutenticacao.addAllowedMethod("GET");
configAutenticacao.addAllowedMethod("DELETE");
configAutenticacao.addAllowedMethod("PUT");
configAutenticacao.addAllowedMethod("OPTIONS");
configAutenticacao.setMaxAge(3600L);
source.registerCorsConfiguration("/**", configAutenticacao);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(-110);
return bean;
}
Upvotes: 1