Spring boot Spring安全Cors启用
我尝试在SpringBoot应用程序中添加一个简单的企业注册。我遵循了吉尔伯特·阿里纳斯匕首在问题中的答案,使用选项1。但是,在尝试使用React访问后端时,我仍然会生成一个CORS错误。 使用Postman,一切都按预期运行,所以我知道我的配置中肯定有一些遗漏,我就是找不到它 我的安全配置文件:Spring boot Spring安全Cors启用,spring-boot,spring-security,Spring Boot,Spring Security,我尝试在SpringBoot应用程序中添加一个简单的企业注册。我遵循了吉尔伯特·阿里纳斯匕首在问题中的答案,使用选项1。但是,在尝试使用React访问后端时,我仍然会生成一个CORS错误。 使用Postman,一切都按预期运行,所以我知道我的配置中肯定有一些遗漏,我就是找不到它 我的安全配置文件: @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class Se
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http .cors().and().csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.addFilter(new JwtAuthenticationFilter(authenticationManager()))
.addFilter(new JwtAuthorizationFilter(authenticationManager(), this.userRepository))
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/login").permitAll()
.antMatchers("/iotd").hasRole("USER")
.anyRequest().authenticated();
}
}
我的档案
@Configuration
public class CorsConfig {
private static final Logger logger = LoggerFactory.getLogger(CorsConfig.class);
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
logger.info("CORS implemented");
registry.addMapping("/**")
.allowedMethods("GET", "POST")
.allowedHeaders("*")
.allowedOrigins("*");
}
};
}
}
启动时,记录器被触发,并表示CORS注册表已实现
然后,我使用CorsConfiguration Bean,按照他的回答中的第二个选项进行操作,但问题仍然存在
我随后使用了一个过滤器方法,但即使在其他SecurityConfig之前应用过滤器,问题仍然存在 在allowedMethods中添加
选项
方法,浏览器出于安全目的发送该方法
某些浏览器会发出此飞行前请求,作为安全措施,以确保服务器信任正在执行的请求。这意味着服务器知道请求中发送的方法、源代码和头可以安全地执行操作。在allowedMethods中添加
选项方法,该方法是客户端浏览器出于安全目的发送的,然后重试。这就成功了。非常感谢你。加上它作为答案,我会接受的