Spring Boot Security No 'Access-Control-Allow-Origin' header is present on the requested resource Error
Asked Answered
I

2

9

I'm building a Spring Boot application with Spring Security. I have a delete functionality which is done through AJAX request using JavaScript's Fetch API. The functionality works correctly in Chrome and Firefox, however it causes problem in Opera. As I mentioned, 'No 'Access-Control-Allow-Origin' header is present on the requested resource' error is shown in the console.

I searched for it, it was because of CORS, browsers normally doesn't allow AJAX requests to different origins, however delete request is in the same domain and if it does work in Chrome/Firefox, I wonder why it doesn't in Opera.

Now, I'm not sharing any code related to application, just because if there was a problem in core, it wouldn't work in other browsers, would it? But in case any code should be shared, please say it, so I'll share. But right now, I don't even know what is wrong. Thanks beforehand.

Invalidism answered 11/8, 2018 at 17:27 Comment(0)
R
10

You can allow your all header by implementing Filter.

Try with this:

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


    @Override
    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", "*");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "*");
        //response.setHeader("Access-Control-Expose-Headers","yourCustomHeaderIfExist");

        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            chain.doFilter(req, res);
        }
    }

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void destroy() {
    }

}

And add @CrossOrigin annotation before your controller.

You can also try with add this bean:

 @Bean
        public WebMvcConfigurer corsConfigurer() {
            return new WebMvcConfigurerAdapter() {
                @Override
                public void addCorsMappings(CorsRegistry registry) {
                    registry.addMapping("/**").allowedOrigins("*").allowedMethods("GET", "POST","PUT", "DELETE");


                }
            };
        }
Richelle answered 11/8, 2018 at 17:33 Comment(7)
Should I register this custom filter somewhere in the Security Config?Invalidism
However, delete functionality still doesn't work in Opera. It's very odd. Console errors are gone. But main problem remains.Invalidism
Access-Control-Allow-Methods. here allow all methodsRichelle
I do.But what's odd to me is that if there'd be a problem it shouldn't work in any browser, no?Invalidism
This is what Opera Console shows, I don't even know that website : "Failed to load floxerz.com/p/…: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'localhost:5000' is therefore not allowed access. The response had HTTP status code 404."Invalidism
i have no idea about opera. i faced this problem when call from angular app. solved this wayRichelle
Anyways, thank you for the response, I'll try to figure somethingInvalidism
C
1

Step 1: Removed all @CrossOrigin inside code

Step 2: Go to Application class and update it with following code

    import java.util.Arrays;
    import java.util.Collections;
    import java.util.stream.Collectors;

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.context.annotation.Bean;
    import org.springframework.http.HttpMethod;
    import org.springframework.web.cors.CorsConfiguration;
    import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
    import org.springframework.web.filter.CorsFilter;

    /**
     * 
     * @author vaquar
     *
     */
    @SpringBootApplication
    public class SpringbootApplication {

        public static void main(String[] args) {
            SpringApplication.run(SpringbootApplication.class, args);
        }
        @Bean
        public CorsFilter corsFilter() {
            final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            final CorsConfiguration config = new CorsConfiguration();
            config.setAllowCredentials(true);
            config.setAllowedOrigins(Collections.singletonList("*"));
            config.setAllowedHeaders(Collections.singletonList("*"));
            config.setAllowedMethods(Arrays.stream(HttpMethod.values()).map(HttpMethod::name).collect(Collectors.toList()));
            source.registerCorsConfiguration("/**", config);
            return new CorsFilter(source);
        }
    }
Corral answered 23/11, 2021 at 8:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.