Springboot整合Security之后出现跨域请求
一、问题描述
本周博主在学习工作流时,临时搭建了一个Springboot整合的activiti框架,准备试一下和bpmn.js交互,但是却在跨域上出现了问题。
但是在我整合好SpringSecurity之前,根据配置好的跨域配置类都是没有问题的,但是整合好之后就出现了问题。
二、问题原因
在查询SpringSecurity配置类的时候发现,SpringSecurity配置类没有添加支持跨域
。即:
@Override
protected void configure(HttpSecurity http) throws Exception {
// 开启跨域访问
http.cors(); //没有设置
....
}
配置类中的http对象没有添加.cors()
。
三、问题解决
根据以上,得出在整合SpringSecurity的项目中,即需要对SpringMVC设置跨域,也需要对SpringSecurity设置跨域。
最后贴上两个配置类的完整代码:
/**
* SpringMVC 跨域配置
*/
@Configuration
public class MvcConfig implements WebMvcConfigurer {
@Bean
public CorsFilter corsFilter() {
final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
final CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowCredentials(true); /*是否允许请求带有验证信息*/
corsConfiguration.addAllowedOrigin("*");/*允许访问的客户端域名*/
corsConfiguration.addAllowedHeader("*");/*允许服务端访问的客户端请求头*/
corsConfiguration.addAllowedMethod("*"); /*允许访问的方法名,GET POST等*/
corsConfiguration.addExposedHeader("token");/*暴露哪些头部信息 不能用*因为跨域访问默认不能获取全部头部信息*/
corsConfiguration.addExposedHeader("TOKEN");
corsConfiguration.addExposedHeader("Authorization");
urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(urlBasedCorsConfigurationSource);
}
}
/**
* SpringSecurity配置类
*/
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 授权
*
* @param http
* @throws Exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
// 开启跨域访问
http.cors(); //.disable();
// 开启模拟请求,比如API POST测试工具的测试,不开启时,API POST为报403错误
http.csrf().disable();
// iframe 跳转错误处理 Refused to display 'url' in a frame because it set 'X-Frame-Options' to 'deny'
http.headers().frameOptions().disable();
// 当出现跨域的OPTIONS请求时,发现被拦截,加入下面设置可实现对OPTIONS请求的放行。
http.authorizeRequests().
requestMatchers(CorsUtils::isPreFlightRequest).
permitAll();
}
}