CORS problem in Spring-Rest API and Ionic3 front-end

Asked

Viewed 214 times

-1

I have developed a Back-end Rest application using spring-Rest and front-end in Ionic. I am facing a CORS configuration problem. In Resources methods I used the annotation @CrossOrigin to free all sources that use the resource, I created a security configuration as below where I have the Bean corsConfigurationSource:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@CrossOrigin (origins = "*")
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private Environment env;

    @Autowired
    private JWTUtil jwtUtil;

    private static final String[] PUBLIC_MATCHERS = {
            "/h2-console/**",
            "/categorias/**",
            "/segmento/**",
            "/fabricantes/**"
    };

    private static final String[] PUBLIC_MATCHERS_GET = {
            "/localidades/estados/**",
            "/localidades/cidades/**",
            "/localidades/bairros/**",
            "/vendedores/"
    };

    private static final String[] PUBLIC_MATCHERS_POST = {
            "/auth/forgot/**",
            "/clientes/**",
            "/clientes/company/**",
            "/vendedores/"
    };

    private static final String[] PUBLIC_MATCHERS_PUT = {
            "/vendedores/"
    };

    private static final String[] PUBLIC_MATCHERS_DELETE = {
            "/vendedores/"
    };

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        if (Arrays.asList(env.getActiveProfiles()).contains("test")) {
            http.headers().frameOptions().disable();
        }

        http.cors().configurationSource(request -> new CorsConfiguration().applyPermitDefaultValues())
        .and().csrf().disable();


        http.authorizeRequests()
            .antMatchers(PUBLIC_MATCHERS).permitAll()
            .antMatchers(HttpMethod.GET, PUBLIC_MATCHERS_GET).permitAll()
            .antMatchers(HttpMethod.POST, PUBLIC_MATCHERS_POST).permitAll()
            .antMatchers(HttpMethod.PUT, PUBLIC_MATCHERS_PUT).permitAll()
            .antMatchers(HttpMethod.DELETE, PUBLIC_MATCHERS_DELETE).permitAll()
            .anyRequest().authenticated();

        http.addFilter(new JWTAuthenticationFilter(authenticationManager(), jwtUtil));
        http.addFilter(new JWTAuthorizationFilter(authenticationManager(), jwtUtil, userDetailsService));
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.addAllowedOrigin("*");
        configuration.addAllowedHeader("*");
        configuration.setAllowedMethods(Arrays.asList("POST", "GET", "PUT", "DELETE", "OPTIONS"));
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);

        return source;
    }

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

When I run the application locally it works perfectly, then I put the API-Rest on Amazon-EC2 to test, when the application tries to consume the API it returns the "error" below.

"has been blocked by CORS policy: Cross origin requests are only supported for Protocol schemes: http, data, Chrome, Chrome-Extension, https"

When I test API end-points with Postman it works perfectly too.

I used this manual to configure, but it’s not working. https://docs.spring.io/spring/docs/4.2.x/spring-framework-reference/html/cors.html

How to configure CORS so that the server does not block requests from other sources?

1 answer

0


I identified the mistake. Calmly analyzing the flaw she cites that the supported requests should respect some informed protocol (http, data, Chrome, Chrome-Extension, https). Then I returned to the base URL configuration which was "ec2-32-17-12-43.sa-East-1.compute.amazonaws.com:8080" and added Http before "http://ec2-32-17-12-43.sa-east-1.compute.amazonaws.com:8080".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.