Search code examples
reactjsspring-bootcorsspotify

CORS policy error - spotify api with Spring boot + React


I am trying to write simple app with spotify api using Spring Boot and React. In spring boot site i have a good working controller:

@RestController
@CrossOrigin()
public class SpotifyTopArtistClient {


    @GetMapping("/artist")
    public SpotifyArtist getTopArtist(OAuth2Authentication details){
        String jwt = ((OAuth2AuthenticationDetails)details.getDetails()).getTokenValue();

        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Authorization","Bearer "+jwt);
        HttpEntity httpEntity = new HttpEntity(httpHeaders);

        ResponseEntity<SpotifyArtist> 
        exchange=restTemplate.exchange("https://api.spotify.com/v1/me/top/artists? 
        time_range=medium_term&limit=1&offset=0", HttpMethod.GET,httpEntity,SpotifyArtist.class);


        return exchange.getBody();
    }

}

In class with the main method I have the bean:

 @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedOrigins("http://localhost:3000")
                        .allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD", "PATCH", "OPTIONS")
                        .allowCredentials(true);
            }
        };
    }

and my security class:

@Configuration
@EnableOAuth2Sso
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/test").authenticated();
        http.authorizeRequests().antMatchers("/artist").authenticated();
        http.authorizeRequests().antMatchers("/login").authenticated();
        http.authorizeRequests().antMatchers("/login/*").authenticated();
        http.cors().and().csrf().disable();
    }
}

When i'm testing endpoint http://localhost:8080/artist in browser and postman - it works as i expected.

On react side i have code:

  componentDidMount(){

    fetch('http://localhost:8080/artist')
    .then(response => response.json())
    .then(data=>{
      console.log(data)
    })
  }

and when i'm trying to run this i see policy-CORS error:

Access to fetch at 'https://accounts.spotify.com/authorize?client_id=8c8db951b0614847b5faf36b300fcb07&redirect_uri=http://localhost:8080/login&response_type=code&scope=user-read-private%20user-read-email%20user-top-read&state=vpHQLG' (redirected from 'http://localhost:8080/artist') from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Why addnotation CrossOrigin above SpotifyTopArtistClient class doesn't work this? Maybe someone have a better experience with spotify api and could help me? Please


Solution

  • Try the following:

    @RestController
    public class SpotifyTopArtistClient {
      (...)
    }
    

    Now update the WebMvcConfigurer:

    @Bean
    public WebMvcConfigurer corsConfigurer() {
       return new WebMvcConfigurer() {
           @Override
           public void addCorsMappings(CorsRegistry registry) {
               registry.addMapping("/**")
                       .allowedOrigins("http://localhost:3000")
                       .allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD", "PATCH", "OPTIONS")
                       .allowCredentials(true);
           }
       };
    }