0
votes

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();
    }

}

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();
    }
}

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("*")
                        .allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD", "PATCH")
                        .allowCredentials(true);
            }
        };
    }

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 '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

3

3 Answers

0
votes

In class with main method i have bean:

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

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();
    }
}
0
votes

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);
       }
   };
}