Spring Boot + Spring Security 应用程序中 POST/PUT/DELETE 请求的 403 响应 [英] 403 response for POST/PUT/DELETE request in spring boot + spring security application
本文介绍了Spring Boot + Spring Security 应用程序中 POST/PUT/DELETE 请求的 403 响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 spring boot rest 应用程序中使用 spring security.Get 请求工作正常,但 POST/PUT/DELETE 请求给出403 Forbidden".下面是我的代码片段.UI 是 Angular 6
I am using spring security in my spring boot rest app. Get requests are working fine but POST/PUT/DELETE request are giving "403 Forbidden". Below is my code snippet. UI is in Angular 6
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserService userService;
@Override
protected void configure(HttpSecurity http) throws Exception {
CustomAuthorizationFilter customAuthorizationFilter = new CustomAuthorizationFilter(authenticationManager());
customAuthorizationFilter.setUserService(userService);
http.cors().and().authorizeRequests().anyRequest().authenticated().and().addFilter(customAuthorizationFilter);
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources", "/configuration/security",
"/swagger-ui.html", "/webjars/**");
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
final CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("*"));
configuration.setAllowedMethods(Arrays.asList("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"));
// setAllowCredentials(true) is important, otherwise:
// The value of the 'Access-Control-Allow-Origin' header in the response must
// not be the wildcard '*' when the request's credentials mode is 'include'.
configuration.setAllowCredentials(true);
// setAllowedHeaders is important! Without it, OPTIONS preflight request
// will fail with 403 Invalid CORS request
configuration.setAllowedHeaders(ImmutableList.of("Authorization", "Cache-Control", "Content-Type"));
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
浏览器响应:
推荐答案
在配置中禁用 csrf
Disable csrf in config
http.csrf().disable().cors().and().....
这篇关于Spring Boot + Spring Security 应用程序中 POST/PUT/DELETE 请求的 403 响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文