Spring Cross Origin
in Java with 0 comment

Spring Cross Origin

in Java with 0 comment

Filter

   public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) 
    throws IOException,ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", 
                           "X-Requested-With, Content-Type, 
                           Authorization, Origin, Accept, Access-Control-Request-Method, 
                           Access-Control-Request-Headers");
        chain.doFilter(req, res);
    }

Annotation

WebMvcConfigurer

@Override
public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/api/**")
        .allowedOrigins("http://domain.com")
        .allowedMethods("PUT", "DELETE")
            .allowedHeaders("header1", "header2", "header3")
        .exposedHeaders("header1", "header2")
        .allowCredentials(false).maxAge(3600);
}

Old XML Way

Note

Responses