【问题标题】:CORS policy error - spotify api with Spring boot + ReactCORS 策略错误 - 使用 Spring Boot + React 发现 api
【发布时间】:2021-11-14 11:47:24
【问题描述】:

我正在尝试使用 Spring Boot 和 React 使用 spotify api 编写简单的应用程序。 在 Spring Boot 站点中,我有一个很好的工作控制器:

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

}

在使用 main 方法的类中,我有 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);
            }
        };
    }

还有我的安全课:

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

当我在浏览器和邮递员中测试端点 http://localhost:8080/artist 时 - 它按我的预期工作。

在反应方面我有代码:

  componentDidMount(){

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

当我尝试运行它时,我看到 policy-CORS 错误:

访问 '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' (从 'http://localhost:8080/artist' 重定向)来自 'http://localhost:3000' 已被 CORS 策略阻止:否 'Access-Control-Allow- Origin' 标头存在于请求的资源上。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。

为什么在 SpotifyTopArtistClient 类上方添加注释 CrossOrigin 不起作用? 也许有人对 spotify api 有更好的体验,可以帮助我吗? 请

【问题讨论】:

    标签: reactjs spring-boot cors spotify


    【解决方案1】:

    尝试以下方法:

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

    现在更新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);
           }
       };
    }
    

    【讨论】:

    • 感谢您的回答。很遗憾,没有变化
    • 这些端点是否经过身份验证?您是否有任何其他全局级别的 CORS 配置?
    • 是的,我在端点“艺术家”上有“antMatchers”。
    • 您能否将这样的 Spring Security 代码添加到您的答案中?
    • 它被后端接受,因为 CORS 仅适用于浏览器中的网页。当调用来自另一个后端服务时,它不会被应用。这就是原因。如果我的回答在某种程度上有帮助,请考虑支持它,甚至接受它是正确的,以便其他人可以从中受益。谢谢!
    猜你喜欢
    • 2021-08-14
    • 2021-01-23
    • 2021-12-25
    • 2021-09-11
    • 2020-05-03
    • 2021-04-19
    • 2019-11-07
    • 2020-05-02
    • 2020-01-31
    相关资源
    最近更新 更多