【发布时间】:2021-07-15 16:09:35
【问题描述】:
我正在尝试在应用了 Spring 5 + Spring Security 5 的项目中实现和使用 Rest API。
在本地运行 Tomcat 后使用 Postman 进行测试时
url: http://localhost:8080/api~
已确认get、post、put等请求正常。
我将此项目上传到 https 服务器,并在本地 Postman 中测试服务器上的 api,
put、post等请求出现403禁止错误,get请求除外。
我google了一下,说是Spring Security的csrf问题+cors处理问题。
所以我就这样改了代码。
- WebSecurityConfig
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/").permitAll()
~
.anyRequest().permitAll()
.and()
.formLogin()
~
.and()
.logout()
~
.and()
.httpBasic().disable().cors().configurationSource(corsConfigurationSource())
.and()
.sessionManagement()
~
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", corsConfiguration);
return source;
}
- WebMvcConfig
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowedOrigins("*");
}
- 控制器
@CrossOrigin("*")
但是在飞行请求中它通常返回 200,但是在这个请求中我仍然得到 403。
哪一部分错了?如果您让我知道,我将不胜感激:)
【问题讨论】:
-
嗨,曼迪,欢迎来到 StackOverflow。这不是一个真正的答案。如果您想添加更多信息或提供不同的示例,请编辑您的原始问题
标签: spring spring-security cors http-status-code-403