Getting CORS policy exception: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. ReactJS/SpringBoot

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.



Read more here: https://stackoverflow.com/questions/67507592/getting-cors-policy-exception-no-access-control-allow-origin-header-is-presen

Content Attribution

This content was originally published by masterYoda at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: