简体   繁体   中英

CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource Spring Boot Rest API & VUE

I have been getting the following errors when making requests from the frontend(built with vue) to the backend(built with spring boot)

Access to XMLHttpRequest at 'http://api.app.com/productorder/all' from origin 'http://my.app.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Here is my WebSecurity Class:

@EnableWebSecurity
public class WebSecurity extends WebSecurityConfigurerAdapter {
    private UserDetailsServiceImpl userDetailsService;
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    @Value("${cors.allowed-origins}")
    private String allowedOrigins;

    public WebSecurity(UserDetailsServiceImpl userDetailsService, BCryptPasswordEncoder bCryptPasswordEncoder) {
        this.userDetailsService = userDetailsService;
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable().authorizeRequests()
                .antMatchers(HttpMethod.POST, SIGN_UP_URL).permitAll()
                .antMatchers("/v2/**", "/configuration/**", "/swagger*/**", "/webjars/**")
                .permitAll()
                .anyRequest().authenticated()
                .and()
                .addFilter(new JWTAuthenticationFilter(authenticationManager()))
                .addFilter(new JWTAuthorizationFilter(authenticationManager()))

                // this disables session creation on Spring Security
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
    }

  @Bean
  CorsConfigurationSource corsConfigurationSource() {
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration().applyPermitDefaultValues();

    config.setExposedHeaders(Arrays.asList("Access-Control-Allow-Headers", "Authorization, x-xsrf-token, Access-Control-Allow-Headers, Origin, Accept, X-Requested-With, " +
            "Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers"));

    // Move this into properties files
    // make sure to split the array before adding below
    config.setAllowedOrigins(Arrays.asList("http://localhost:3000","http://localhost:8080","http://my.app.com", "http://api.app.com"));
    config.setAllowedMethods(Arrays.asList("GET","POST", "UPDATE", "DELETE", "OPTIONS", "PUT"));

    source.registerCorsConfiguration("/**", config);
    return source;
  }
}

Create a Once per request filter add this response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT, PATCH"); response.setHeader("Access-Control-Allow-Headers", "Date, Content-Type, Accept, X-Requested-With, Authorization, From, X-Auth-Token, Request-Id"); response.setHeader("Access-Control-Expose-Headers", "Set-Cookie"); response.setHeader("Access-Control-Allow-Credentials", "true"); response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT, PATCH"); response.setHeader("Access-Control-Allow-Headers", "Date, Content-Type, Accept, X-Requested-With, Authorization, From, X-Auth-Token, Request-Id"); response.setHeader("Access-Control-Expose-Headers", "Set-Cookie"); response.setHeader("Access-Control-Allow-Credentials", "true");

Use CorsConfiguration#setAllowedHeaders(List<String> allowedHeaders) ( quote ):

Set the list of headers that a pre-flight request can list as allowed for use during an actual request. The special value "*" allows actual requests to send any header.

A header name is not required to be listed if it is one of: Cache-Control, Content-Language, Expires, Last-Modified, or Pragma.

By default this is not set.

For example, add in the corsConfigurationSource() method:

config.setAllowedHeaders(Arrays.asList("Access-Control-Allow-Origin", "Authorization", "Accept", "Content-Type"));

Notice that you may not need Authorization if it isn't used and may need to add other headers as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM