Home > Software engineering >  Unable to resolve CORS errors
Unable to resolve CORS errors

Time:01-06

Assumptions

We are developing a web application with the following library.
When a request is sent from the front end to the back end, a CORS error occurs.

  • Frontend: Vue.js (Version: 3)
  • Backend: SpringBoot (version: 2.7.6)
  • Authentication: SpringSecurity

What we want to achieve

We would like to resolve the following CORS errors that occur when a request is sent from the front-end side to the back-end side. enter image description here

Access to XMLHttpRequest at 'http://localhost:8085/users/profile/1' from origin 'http://localhost:8888' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Source code

Send request to Spring in Vue.js (Edit.vue)

    onClickDelete() {
      const path = 'users/profile/'
      axios.delete(
          process.env.VUE_APP_ROOT_API   path   this.$store.state.user_id,{
            headers: {
              "Authorization": "Bearer "   this.$store.state.jwt_token,
            },
          })
          .then(response => {
          })
          .catch(error => {
            console.log(error)
          })
    },

Receiving process in Spring (UsersController.java)

@RestController
@RequestMapping("/users/profile")
public class UsersController {
    @DeleteMapping("/{user_id}")
    @ResponseStatus(code = HttpStatus.NO_CONTENT, value = HttpStatus.NO_CONTENT)
    public void profiledelete(@PathVariable("user_id") Long id) throws Exception {
    }
}

SpringSecurity configuration file (WebSecurityConfig.java)

@Profile("production")
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserRepository userRepository;
    private final JsonRequestAuthenticationProvider jsonRequestAuthenticationProvider;
    @Value("${security.secret-key:secret}")
    private String secretKey = "secret";

    public WebSecurityConfig(JsonRequestAuthenticationProvider jsonRequestAuthenticationProvider// ,
    ) {
        this.jsonRequestAuthenticationProvider = jsonRequestAuthenticationProvider;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        JsonRequestAuthenticationFilter jsonAuthFilter =
                new JsonRequestAuthenticationFilter(userRepository);
        jsonAuthFilter.setAuthenticationManager(authenticationManagerBean());
        http.cors().configurationSource(request -> new CorsConfiguration().applyPermitDefaultValues());
        http.addFilter(jsonAuthFilter);
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .exceptionHandling().accessDeniedHandler(accessDeniedHandler())
                .and()
                .csrf().
                    disable()
                .addFilterBefore(tokenFilter(), UsernamePasswordAuthenticationFilter.class)
                .sessionManagement()
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        ;
    }

What we tried

@CrossOrigin to the process (UsersController.java) that receives the process in Spring

What we did

Receive process in Spring (UsersController.java)

@RestController
@RequestMapping("/users/profile")
@CrossOrigin
public class UsersController {
    @DeleteMapping("/{user_id}")
    @ResponseStatus(code = HttpStatus.NO_CONTENT, value = HttpStatus.NO_CONTENT)
    public void profiledelete(@PathVariable("user_id") Long id) throws Exception {
    }
}
Result

The CORS error is still displayed.

Additional Information

  • Before SpringSecurity was installed, I think that granting @CrossOrigin on the Spring side solved the CORS error.
  • When the GET method is used in other requests, it succeeds without any CORS errors with the Spring side.

CodePudding user response:

This seems to be an issue with your setup with spring security. There are two primary ways to fix this error. However i would also recommend upgrading to a newer version of spring security, because WebSecurityConfigurerAdapter has now been deprecated

Primary method

CORS on Spring security (2.x)

@Profile("production")
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserRepository userRepository;
    private final JsonRequestAuthenticationProvider jsonRequestAuthenticationProvider;
    @Value("${security.secret-key:secret}")
    private String secretKey = "secret";

    public WebSecurityConfig(JsonRequestAuthenticationProvider jsonRequestAuthenticationProvider// ,
    ) {
        this.jsonRequestAuthenticationProvider = jsonRequestAuthenticationProvider;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        JsonRequestAuthenticationFilter jsonAuthFilter =
                new JsonRequestAuthenticationFilter(userRepository);
        jsonAuthFilter.setAuthenticationManager(authenticationManagerBean());
        http.cors();
        http.addFilter(jsonAuthFilter);
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .exceptionHandling().accessDeniedHandler(accessDeniedHandler())
                .and()
                .csrf().
                    disable()
                .addFilterBefore(tokenFilter(), UsernamePasswordAuthenticationFilter.class)
                .sessionManagement()
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        ;
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
// -- CHANGE CODE HERE --
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

CORS disable

@Profile("production")
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserRepository userRepository;
    private final JsonRequestAuthenticationProvider jsonRequestAuthenticationProvider;
    @Value("${security.secret-key:secret}")
    private String secretKey = "secret";

    public WebSecurityConfig(JsonRequestAuthenticationProvider jsonRequestAuthenticationProvider// ,
    ) {
        this.jsonRequestAuthenticationProvider = jsonRequestAuthenticationProvider;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        JsonRequestAuthenticationFilter jsonAuthFilter =
                new JsonRequestAuthenticationFilter(userRepository);
        jsonAuthFilter.setAuthenticationManager(authenticationManagerBean());
        http.cors().disable();
        http.addFilter(jsonAuthFilter);
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .exceptionHandling().accessDeniedHandler(accessDeniedHandler())
                .and()
                .csrf().
                    disable()
                .addFilterBefore(tokenFilter(), UsernamePasswordAuthenticationFilter.class)
                .sessionManagement()
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        ;
    }

CORS on Spring security (3.x)

@Configuration
public class WebConfiguration implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedMethods("*");
    }
}

always go for the second method

CodePudding user response:

Have you tried http.authorizeRequests().cors().disable().XXXXX ? It fixed cors problems for me

  • Related