Search code examples
javareactjsspringfiltercors

React client headers are missing in the server spring boot - while they do arrive with postman


I have a React client app which is making Http Get to the server

  export const restApiGet = async (apiPath: string) => {
    const headers  = {
      'token': 'aaaa',
      'postman-token': 'bbbb',
    };
    return Axios.get(`${apiUrl}${apiPath}`, {
      withCredentials: true, // Include cookies in the request
      headers: headers
    }
    );
  };

the request arrive to the server which is spring boot java

but in My server I have a filter, I need to read the token header

@Component
@WebFilter
public class UserIdFilter implements Filter {

    //TODO add filter for all response if object has userId column it must match the userId of the token
    private final AbstractCacheService abstractCacheService;

    public UserIdFilter(AbstractCacheService abstractCacheService) {
        this.abstractCacheService = abstractCacheService;
    }
    

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
       
}

But in the server when I try to get the header its null

If i look on the request on Chrome - i convert the header from token - to Token. but also reading Token from headers dont bring any results

If i copy the Chrome request to postman the header arrive to postman

i have set on etc host - windows - 127.0.0.1 to localhost and I call to localhost as well.

How can I help the server to see the token ? it feels the problem is on react since with postman all is working I tried also to play with cros filter setting- to allow, but still same issue

@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**")
            .allowedOriginPatterns("*") // Allow requests from any origin
            .allowedMethods("*") // Allow all HTTP methods (GET, POST, PUT, DELETE, etc.)
            .allowedHeaders("*") // Allow all headers
            .exposedHeaders("*") // Expose all headers
            .allowCredentials(true);//.allowedOriginPatterns("*"); // Allow credentials (e.g., cookies)

}

Solution

  • Fixed by adding this cors filter setting

    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    
    @Configuration
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.headers().cacheControl();
            http.csrf().disable(); // Disable CSRF
            http.cors();
        }
    }