katahik
katahik

Reputation: 477

Unable to resolve CORS errors

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.

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

Upvotes: 0

Views: 1465

Answers (1)

Ryan The Ghost
Ryan The Ghost

Reputation: 177

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().configurationSource(request -> {
      var cors = new CorsConfiguration();
      cors.setAllowedOrigins(List.of("*"));
      cors.setAllowedMethods(List.of("GET","POST", "PUT", "DELETE", "OPTIONS"));
      cors.setAllowedHeaders(List.of("*"));
      return cors;
    });
        http.addFilter(jsonAuthFilter);
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .exceptionHandling().accessDeniedHandler(accessDeniedHandler())
                .and()
                .csrf().
                    disable()
                .addFilterBefore(tokenFilter(), UsernamePasswordAuthenticationFilter.class)
                .sessionManagement()
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        ;
    }

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.

Upvotes: 1

Related Questions