虽然我们在WebMvcConfigurer中设置跨域,但是如果WebSecurityConfigurerAdapter中不设置http.cors(),会导致一个的问题:
如果一个需要被spring security过滤器验证的请求,比如对url“/getInfo”的请求,如果这个请求没有通过验证,比如没有携带token或token不正确,
导致没有给该请求发放authentication,那么这个请求会在后续的Authentication过滤器中被认定鉴权失败,直接返回response给客户端。
这种情况下请求将不会交给WebMvcConfigurer的跨域过滤器,
而WebMvcConfigurer的跨域过滤器会给response header中添加“Access-Control-Allow-Origin”字段,
该字段表示服务器接收此Origin的跨域请求。
由于该请求不会经过WebMvcConfigurer的过滤器,因此响应头中不会携带“Access-Control-Allow-Origin”字段,
导致虽然请求正确在服务器处理了,也把响应发回给浏览器了,但是浏览器认为服务器不接受该地址的跨域请求,
不会将response传递给页面脚本,并且提示该服务器禁止此Origin的跨域请求
故在SpringBoot中使用Spring Security,需要在WebSecurityConfigurerAdapter和WebMvcConfigurer中同时开启跨域。
@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception { //不要忘记配置跨域!
http.cors().and().csrf().disable();
...
}
}
感谢这位大哥的帮助才解决这个问题!
这是原文链接:
https://blog.youkuaiyun.com/mr_orange_klj/article/details/108984354
本文详细解析了在SpringBoot项目中使用SpringSecurity时遇到的跨域问题,并提供了具体的解决方案,包括如何在WebSecurityConfigurerAdapter中正确配置跨域。
2402

被折叠的 条评论
为什么被折叠?



