Spring Security CORS不适用于Http PUT方法

okxuctiv  于 2023-04-04  发布在  Spring
关注(0)|答案(6)|浏览(127)

我在Postman中尝试PutMapping我的API时得到了“无效的CORS请求”。但它在“POST”和“GET”Map中工作正常。
为什么它不适用于“PUT”操作?
我的Sping Boot 版本:2.0
这是我的配置:

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



    http.cors().and().csrf().disable()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .authorizeRequests()
            .antMatchers("/h2-console/**/**").permitAll()
            .antMatchers(HttpMethod.GET,"/user/get-request").permitAll()
            .antMatchers(HttpMethod.POST,"/user/post-request").permitAll()
            .antMatchers(HttpMethod.PUT,"/user/put-request").permitAll()
            .and()
            .exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint)
            .and()
            .addFilter(new JwtAuthenticationFilter(authenticationManager()))
            .addFilter(new JwtAuthorizationFilter(authenticationManager(), jwtUserDetailService));



}

@Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedOrigins("*").allowedHeaders("*").exposedHeaders("Authorization");

            }
        };
    }

这是我的控制器:

@RestController
@RequestMapping("/user")
public class UserController {

@PutMapping("/put-request")
public void doResetPassword(@RequestBody String password) {
    System.out.println("PUT MAPPING");

}

@PostMapping("/post-request")
public void doResetPassword(@RequestBody String password) {
    System.out.println("POST MAPPING");

}

@GetMapping("/get-request")
public void doResetPassword() {
    System.out.println("GET MAPPING");

}

}
yvfmudvl

yvfmudvl1#

@Configuration
public class CrossOriginConfig {

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

}
uemypmqf

uemypmqf2#

@Bean
public CorsConfigurationSource corsConfigurationSource() {
    final CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(ImmutableList.of("*"));
    configuration.setAllowedMethods(ImmutableList.of("HEAD",
            "GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"));
    configuration.setAllowCredentials(true);
    configuration.setAllowedHeaders(ImmutableList.of("*"));
    configuration.setExposedHeaders(ImmutableList.of("X-Auth-Token","Authorization","Access-Control-Allow-Origin","Access-Control-Allow-Credentials"));
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

我通过添加这个bean来允许cors请求。你可以根据需要配置setAllowedHeaders()和setExposedHeaders()。
另外,我把这一行添加到我的控制器;

@RequestMapping(value = "/auth")
@RestController
@CrossOrigin(origins = "*") //this line
public class AuthenticationController {..}

如果您的控制器需要处理动态OPTION请求,您可以将此方法添加到您的控制器。您可以通过端点配置该值。

@RequestMapping(value = "/**/**",method = RequestMethod.OPTIONS)
public ResponseEntity handle() {
    return new ResponseEntity(HttpStatus.OK);
}
tvokkenx

tvokkenx3#

如果您使用的是IIS服务器,这是一个问题,与WebDAVModule似乎阻止PUT和DELETE方法默认!

<system.webServer>
  <modules runAllManagedModulesForAllRequests="false">
    <remove name="WebDAVModule" />
  </modules>
</system.webServer>

我真的希望没有人会因为这个而痛苦!=]
字体:https://mozartec.com/asp-net-core-error-405-methods-not-allowed-for-put-and-delete-requests-when-hosted-on-iis/

ylamdve6

ylamdve64#

在Spring中,我使用Kotlin做了以下事情:

@Bean
fun corsConfigurationSource(): CorsConfigurationSource? {
    val source = UrlBasedCorsConfigurationSource()

    val corsConfig = CorsConfiguration()
        .applyPermitDefaultValues()
        .setAllowedOriginPatterns(listOf("*"))
    corsConfig.addAllowedMethod(HttpMethod.PUT)
    source.registerCorsConfiguration("/**", corsConfig)

    return source
}
m4pnthwp

m4pnthwp5#

我只想补充三点。
1.接受的答案和下面的答案是错误的CORS方法。如果您试图配置CORS,这意味着您正在尝试使您的API只能由您知道的一些客户端访问。

configuration.setAllowedOrigins(ImmutableList.of("*")); // from the first answer

.addMapping("/**") // from the second answer

使API可被任何客户端访问。如果这是您想要的,您可以只执行以下操作,而不需要配置另一个bean

http.cors().disable()

1.问题中的问题可能会发生在你允许使用http的origin并使用https执行请求时。所以要注意这两个是不同的。
1.下面是一个工作配置

// In the import section
import static org.springframework.security.config.Customizer.withDefaults;

// In the HttpSecurity configuration
http.cors(withDefaults())

 @Bean
 public CorsConfigurationSource corsConfigurationSource() {
   final CorsConfiguration configuration = new CorsConfiguration();
   configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200", "https://localhost:4200"));
   configuration.setAllowedMethods(Arrays.asList("HEAD",
         "GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"));
   configuration.setAllowCredentials(true);
   configuration.setAllowedHeaders(Arrays.asList("Content-Type", "X-Auth-Token","Authorization","Access-Control-Allow-Origin","Access-Control-Allow-Credentials"));
   configuration.setExposedHeaders(Arrays.asList("Content-Type", "X-Auth-Token","Authorization","Access-Control-Allow-Origin","Access-Control-Allow-Credentials"));
   final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
   source.registerCorsConfiguration("/**", configuration);
   return source;
 }
g52tjvyc

g52tjvyc6#

我使用的是Spring SecuritySping Boot 2.1.2。在我的具体案例中,PUT调用是在我从CorsConfigurationSource bean中显式声明setAllowedMethods()中的“PUT”方法后工作的。可以根据应用程序的行为选择头。

@Bean
CorsConfigurationSource corsConfigurationSource() {
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    final String headers =  "Authorization, Access-Control-Allow-Headers, "+
                            "Origin, Accept, X-Requested-With, Content-Type, " + 
                            "Access-Control-Request-Method, Custom-Filter-Header";
    
    CorsConfiguration config = new CorsConfiguration();

    config.setAllowedMethods(Arrays.asList("GET","POST","PUT","DELETE")); // Required for PUT method
    config.addExposedHeader(headers);
    config.setAllowCredentials(true);
    config.applyPermitDefaultValues();
    
    source.registerCorsConfiguration("/**", config);
    
    return source;
}

相关问题