[Vuejs]-How I can fix broken CORS In Spring Boot + Vue app?

3๐Ÿ‘

โœ…

I think that you do not need the class CorsConfiguration.

You do not need to annotate with CrossOrigin the SpotifyApiController either.

The configuration of CORS ideally should be placed in the security configuration. Something like that (in OAuth2Configuration):

import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter;

@Configuration
@EnableOAuth2Sso
@EnableWebSecurity
public class OAuth2Configuration extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
  // The configuration that you needed

  // If preflight requests are redirected by OAuth conf, you can try adding:
  // .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()

  // CORS configuration

  // This value must be parameterized according to your application needs 
  final String corsOrigin="http://localhost:8081";
  // The idea is to insert the CORS filter before the filter injected by
  // the @EnableOAuth2Sso annotation
  http.addFilterBefore(new CorsFilter(corsConfigurationSource(corsOrigin)), AbstractPreAuthenticatedProcessingFilter.class);
}

private CorsConfigurationSource corsConfigurationSource(String corsOrigin) {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList(corsOrigin));
    configuration.setAllowedMethods(Arrays.asList("GET","POST","HEAD","OPTIONS","PUT","PATCH","DELETE"));
    configuration.setMaxAge(10L);
    configuration.setAllowCredentials(true);
    configuration.setAllowedHeaders(Arrays.asList("Accept","Access-Control-Request-Method","Access-Control-Request-Headers",
      "Accept-Language","Authorization","Content-Type","Request-Name","Request-Surname","Origin","X-Request-AppVersion",
      "X-Request-OsVersion", "X-Request-Device", "X-Requested-With"));
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}


๐Ÿ‘คjccampanero

0๐Ÿ‘

There is a sample of RestConfiguration corsfilter. You can add the following bean to your code:

@CrossOrigin
@Configuration
public class RestConfiguration {

  @Bean
  public FilterRegistrationBean corsFilter() {

    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("*");
    config.addAllowedHeader("*");
    config.addAllowedMethod("OPTIONS");
    config.addAllowedMethod("GET");
    config.addAllowedMethod("PUT");
    config.addAllowedMethod("POST");
    config.addAllowedMethod("DELETE");
    config.addAllowedMethod("PATCH");

    source.registerCorsConfiguration("/**", config);
    final FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
    bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
    return bean;
  }
}
๐Ÿ‘คOktay Alizada

0๐Ÿ‘

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().configurationSource(request -> {
            CorsConfiguration cors = new CorsConfiguration();
            cors.setAllowedOrigins(
                    Lists.newArrayList("*"));
            cors.setAllowedMethods(Lists.newArrayList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
            cors.setAllowedHeaders(Lists.newArrayList("*"));
            return cors;
        }).and().csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .authorizeRequests()
                .antMatchers("")
                .permitAll().and()
                .addFilterBefore(setLoginProcessingFilter(), UsernamePasswordAuthenticationFilter.class);
    }
๐Ÿ‘คSantosh b

0๐Ÿ‘

Did you try using @CrossOrigin(origins="http://localhost:8081") on your controller class and repository class?

Also in conjuction to it : Try to add WebConfigurer Bean in you main SpringBoot Application class and annonate that too with @CrossOrigin(origins="http://localhost:8081")

@Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                System.out.println("here");
                registry.addMapping("/**").allowedOrigins("http://localhost:8081").allowedMethods("PUT", "DELETE" )
                .allowedHeaders("header1", "header2", "header3")
                .exposedHeaders("header1", "header2")
                .allowCredentials(false).maxAge(3600);;
            }
        };
    }

Please visit this link too for enabling CORS in your application server side and check as per your configuration which CORS method you can use.

๐Ÿ‘คAbhishek

Leave a comment