-2

Well, this is my Exception I get in the browser:

Access to XMLHttpRequest at 'http://localhost:8080/home/data' from origin 'http://localhost:3000' 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.

The Backend is a Spring Security Application and the Frontend is a ReactJS application. On the frontend I'd like to send a GET request to the backend with login information. This is the code in the frontend:

function make_base_auth(user, password) {
    var tok = user + ':' + password;
    var hash = btoa(tok);
    return 'Basic ' + hash;
}

export default class Login extends Component {

    

    getData() {
        $.ajax({
            type: 'GET',
            url: 'http://localhost:8080/home/data',
            dataType: 'json',
            //whatever you need
            beforeSend: function (xhr) {
                xhr.setRequestHeader('Authorization', make_base_auth('fabian.graml@gmail.com', 'password'));
            },
            success: function(response){
                console.log(response)
            }
        });
    }

The getData() function is executed when you click on a text on the page.

As mentioned the Backend is a Spring Boot Application.

This is my SecurityConfiguration.java:

@Configuration
@EnableWebSecurity
@AllArgsConstructor
public class SecurityConfiguration extends WebSecurityConfigurerAdapter{

    private final CustomUserService customUserService;

    @Bean
    public BCryptPasswordEncoder encodePasswd() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors()
                .and()
                .authorizeRequests()
                .antMatchers("/home/**")
                .authenticated();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(daoAuthenticationProvider());
    }

    @Bean
    public DaoAuthenticationProvider daoAuthenticationProvider(){
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setPasswordEncoder(new BCryptPasswordEncoder());
        provider.setUserDetailsService(customUserService);
        return provider;
    }
    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.addAllowedHeader("Access-Control-Allow-Origin");
        configuration.setAllowedMethods(Arrays.asList("GET","POST"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

}

And this is my CorsConfiguration.java

@Configuration
public class CorsConfiguration {

    @Bean
    public WebMvcConfigurer corsConfigurer(){
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedMethods("GET", "POST", "PUT", "DELETE")
                        .allowedHeaders("**")
                        .allowedOrigins("**");

            }
        };
    }
}

My question: Does somone know how to fix this exception or to turn off CORS? Would be great if someone can help me with my problem.

  • When you build the production version of your react app, if you move those production files to your spring boot application and serve them through that, you won't get a cors error because then both your api and frontend will have the same origin. Something to consider because you only have a server for react in development mode. The drawback being you would have to build the react app each time you wanted to test it. A possible solution if you cannot find another. – Danoram May 12 '21 at 17:10
  • Your values are wrong. `.allowedOrigins("**");` and `.allowedOrigins("**")` are not valid. You have to use `*` (only one wildcard). – dur May 15 '21 at 09:11
  • You also have to change `configuration.addAllowedHeader("Access-Control-Allow-Origin");` to `configuration.addAllowedHeader("*");` to allow all headers. – dur May 15 '21 at 09:16

1 Answers1

-1

I think you need to add @CrossOrigin(origins = "*", maxAge = 3600) annotation in your controller