Spring CORS No 'Access-Control-Allow-Origin' header is present

后端 未结 11 1122
半阙折子戏
半阙折子戏 2020-11-30 18:21

I am getting the following problem after porting web.xml to java config

No \'Access-Control-Allow-Origin\' header is present on the requested resource. Origi         


        
相关标签:
11条回答
  • 2020-11-30 18:59

    as @Geoffrey pointed out, with spring security, you need a different approach as described here: Spring Boot Security CORS

    0 讨论(0)
  • 2020-11-30 19:00

    For some reason, if still somebody not able to bypass CORS, write the header which browser wants to access your request.

    Add this bean inside your configuration file.

    @Bean
    public WebSecurityConfigurerAdapter webSecurity() {
        return new WebSecurityConfigurerAdapter() {
    
            @Override
            protected void configure(HttpSecurity http) throws Exception {
                http.headers().addHeaderWriter(
                        new StaticHeadersWriter("Access-Control-Allow-Origin", "*"));
    
    
            }
        };
    }
    

    This way we can tell the browser we are allowing cross-origin from all origin. if you want to restrict from specific path then change the "*" to {'http://localhost:3000',""}.

    Helpfull reference to understand this behaviour https://www.concretepage.com/spring-4/spring-4-rest-cors-integration-using-crossorigin-annotation-xml-filter-example

    0 讨论(0)
  • 2020-11-30 19:02

    public class TrackingSystemApplication {

        public static void main(String[] args) {
            SpringApplication.run(TrackingSystemApplication.class, args);
        }
    
        @Bean
        public WebMvcConfigurer corsConfigurer() {
            return new WebMvcConfigurerAdapter() {
                @Override
                public void addCorsMappings(CorsRegistry registry) {
                    registry.addMapping("/**").allowedOrigins("http://localhost:4200").allowedMethods("PUT", "DELETE",
                            "GET", "POST");
                }
            };
        }
    
    }
    
    0 讨论(0)
  • 2020-11-30 19:09

    Change the CorsMapping from registry.addMapping("/*") to registry.addMapping("/**") in addCorsMappings method.

    Check out this Spring CORS Documentation .

    From the documentation -

    Enabling CORS for the whole application is as simple as:

    @Configuration
    @EnableWebMvc
    public class WebConfig extends WebMvcConfigurerAdapter {
    
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**");
        }
    }
    

    You can easily change any properties, as well as only apply this CORS configuration to a specific path pattern:

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

    Controller method CORS configuration

    @RestController
    @RequestMapping("/account")
    public class AccountController {
      @CrossOrigin
      @RequestMapping("/{id}")
      public Account retrieve(@PathVariable Long id) {
        // ...
      }
    }
    

    To enable CORS for the whole controller -

    @CrossOrigin(origins = "http://domain2.com", maxAge = 3600)
    @RestController
    @RequestMapping("/account")
    public class AccountController {
    
        @RequestMapping("/{id}")
        public Account retrieve(@PathVariable Long id) {
            // ...
        }
    
        @RequestMapping(method = RequestMethod.DELETE, path = "/{id}")
        public void remove(@PathVariable Long id) {
            // ...
        }
    }
    

    You can even use both controller-level and method-level CORS configurations; Spring will then combine attributes from both annotations to create merged CORS configuration.

    @CrossOrigin(maxAge = 3600)
    @RestController
    @RequestMapping("/account")
    public class AccountController {
    
        @CrossOrigin("http://domain2.com")
        @RequestMapping("/{id}")
        public Account retrieve(@PathVariable Long id) {
            // ...
        }
    
        @RequestMapping(method = RequestMethod.DELETE, path = "/{id}")
        public void remove(@PathVariable Long id) {
            // ...
        }
    }
    
    0 讨论(0)
  • 2020-11-30 19:09

    I also had messages like No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access.

    I had configured cors properly, but what was missing in webflux in RouterFuncion was accept and contenttype headers APPLICATION_JSON like in this piece of code:

    @Bean
    RouterFunction<ServerResponse> routes() {
        return route(POST("/create")
                                  .and(accept(APPLICATION_JSON))
                                  .and(contentType(APPLICATION_JSON)), serverRequest -> create(serverRequest);
    }
    
    0 讨论(0)
提交回复
热议问题