Springfox 上的 Spring Boot 应用程序用于 swagger-ui PUT 始终“无效的 CORS 请求”

问题描述 投票:0回答:1

我有一个基于 1.5.3.RELEASE 的 Spring Boot 应用程序,它在 2.6.1 中利用 springfox-swagger2 ,在 2.6.1 中利用 springfox-swagger-ui 。

对于大多数 API 来说,一切都很好。 GET 有效。帖子有效。 PUT 总是在 swagger-ui.html 处出错

Invalid CORS request
我可以通过像这样的请求重现问题 localhost

$ curl -i -X PUT 'http://localhost.mycompany.com:8080/mom/749f4f1f-0769-488d-9776-17fc3927cfc6/description?description=WangoTango' \
> -H 'Origin: http://example.com' \
> -H 'Cookie: a.token_key=redacted' \
> -H 'accept: application/json'
HTTP/1.1 403
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: SAMEORIGIN
Content-Length: 20
Date: Sat, 11 Nov 2023 01:42:01 GMT

Invalid CORS request

我的应用程序是根据 https://docs.spring.io/spring-security/reference/reactive/integrations/cors.html 使用 CorsConfigurationSource

进行配置的
/**
 * CORS Configuration lifted from https://docs.spring.io/spring-security/reference/reactive/integrations/cors.html;
 * configure to allow all origins, all methods.
 */
@Configuration
public class CorsConfig {

  @Bean
  CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList("*"));
    configuration.setAllowedMethods(Arrays.asList("*"));
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
  }

在控制器中..端点也配置了非常宽松的 CrossOrigin 注释...

  @RequestMapping(
      method = RequestMethod.PUT,
      path = "/mom/{verId:.+}/description",
      produces = {"application/json"})
  @CrossOrigin
  @ApiOperation(value = "Set the description")
  @ApiResponses(value = {
          @ApiResponse(code = 200, message = "Success", response = MBom.class),
          @ApiResponse(code = 400, message = "Bad Request", response = String.class),
          @ApiResponse(code = 404, message = "Error", response = String.class)})
  public ResponseEntity<?> setDescription(
      @PathVariable("verId") String verId,
      @RequestParam("description") String description) {
...

Spring Boot 1.5.3.RELEASE 应用程序中用于使 PUT 端点与 CORS 配合使用的神奇配置是什么?我之前在 StackOverflow 上找到的任何答案都没有成功。

java spring-boot cors swagger-ui
1个回答
0
投票

尝试在

PUT
 中传递显式方法名称,如 
POST
*
 而不是 
CorsConfiguration.setAllowedMethods

更新至此:

configuration.setAllowedMethods(Arrays.asList("GET, PUT, POST, PATCH"));
© www.soinside.com 2019 - 2024. All rights reserved.