我收到了无效的CORS请求'当我在Postman中尝试PutMapping
我的API时。但它适用于' POST'并且' GET'映射。
为什么它不适用于' PUT'操作
My 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");
}
};
}
这是我的控制者:
@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");
}
}
答案 0 :(得分:5)
@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);
}
答案 1 :(得分:0)
使用此:
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
答案 2 :(得分:0)
比接受的解决方案简单得多。
@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");
}
};
}
}
答案 3 :(得分:0)
如果您使用的是 IIS 服务器 这是 WebDAVModule 的问题,它似乎默认阻止 PUT 和 DELETE 方法!
<system.webServer>
<modules runAllManagedModulesForAllRequests="false">
<remove name="WebDAVModule" />
</modules>
</system.webServer>
我真的希望没有其他人为此感到痛苦! =]
答案 4 :(得分:0)
在使用 Kotlin 的 Spring 中,我做了以下事情:
@Bean
fun corsConfigurationSource(): CorsConfigurationSource? {
val source = UrlBasedCorsConfigurationSource()
val corsConfig = CorsConfiguration()
.applyPermitDefaultValues()
.setAllowedOriginPatterns(listOf("*"))
corsConfig.addAllowedMethod(HttpMethod.PUT)
source.registerCorsConfiguration("/**", corsConfig)
return source
}
答案 5 :(得分:0)
我只想添加三件事。
接受的答案及其下面的答案是执行 CORS 的错误方法。 如果您正在尝试配置 CORS,则意味着您正在尝试使您的 API 只能由您认识的一些客户端访问。线条
configuration.setAllowedOrigins(ImmutableList.of("*")); // from the first answer
.addMapping("/**") // from the second answer
使任何客户端都可以访问该 API。如果这就是您想要的,您只需执行以下操作而无需配置另一个 bean
http.cors().disable()
当您使用 http
允许来源并使用 https
执行您的请求时,可能会出现问题中的问题。所以请注意,这两个是不同的。
下面是一个工作配置
// 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;
}