Cors not working for my spring boot application

Here is my webConfig

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }
}

I have an endpoint /healththat returns some health data and works fine.

Here is the junit test

@Test
    public void corsTest() {
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.ORIGIN, "http://localhost:9000");
        HttpEntity<?> requestEntity = new HttpEntity(headers);
        ResponseEntity<Status> entity = this.restTemplate.exchange("/health", HttpMethod.GET, requestEntity, Status.class);
        assertEquals(HttpStatus.OK, entity.getStatusCode());
        assertEquals("http://localhost:9000", entity.getHeaders().getAccessControlAllowOrigin()); //6
        Status health = entity.getBody();
        assertThat(health.getAppName()).isEqualTo(appName);
    }

The test fails on line 6. If you comment out this line, the test passes. Through the debugger, I found that entity.getHeaders().getAccessControlAllowOrigin()it is null. I used this sample application as a reference and it works great. but for my application it does not work.

when i use javascript to call / health api i see cors working. If I comment on the webConfig class, I get an error in javascript. Debugging more on javascript shows that the cors response header is not set, but the request worked successfully when webconfig is enabled.

cors. , . , , .

+4
3

, , , , .

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class SimpleCORSFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Headers", "Origin,Accept,X-Requested-With,Content-Type,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization");
        if(request.getMethod().equals(HttpMethod.OPTIONS.name())){
            response.setStatus(HttpStatus.NO_CONTENT.value());
        }else{
            chain.doFilter(req, res);
        }
    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}
}
+9

, corsfilter errorPageFilter spring . CORS , . @Order(Ordered.HIGHEST_PRECEDENCE), .

+3

I assume that you did not use annotation dependent configuration, but java config one.

In this case, I see the difference in the above example and the example from github.

Last uses

registry.addMapping("/greeting-javaconfig").allowedOrigins("http://localhost:9000");

while your example skips allowOrigins

registry.addMapping("/greeting-javaconfig");

I think it matters here.

0
source

Source: https://habr.com/ru/post/1655510/


All Articles