Spring Security CORS不适用于Http PUT方法

Sam*_*ıcı 6 security spring put cors spring-boot

当我尝试PutMapping在Postman中使用我的API 时,我收到“无效的CORS请求” 。但这对于“ POST”和“ GET”映射工作正常。

为什么对“ PUT”操作不起作用?

我的Spring 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");

            }
        };
    }
Run Code Online (Sandbox Code Playgroud)

这是我的控制器:

@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");


}

}
Run Code Online (Sandbox Code Playgroud)

Rar*_*ean 9

它比公认的解决方案简单得多。

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

}
Run Code Online (Sandbox Code Playgroud)

  • 这有效!并且比公认的解决方案更简单。谢谢! (2认同)

小智 6

@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;
}
Run Code Online (Sandbox Code Playgroud)

通过添加此bean,我设法允许cors请求。您可以根据需要配置setAllowedHeaders()和setExposedHeaders()。

另外,我将此行添加到了控制器中。

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

如果您的控制器需要处理即时的OPTION请求,则可以将此方法添加到控制器中。您可以按端点配置值。

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