WebMvcConfigurer 与 WebSecurityConfigurerAdapter

SpringBoot中使用Spring Security,需要在WebSecurityConfigurerAdapter和WebMvcConfigurer中同时开启跨域

首先在WebMvcConfigurer中开启跨域

@Configuration
public class WebConfig implements WebMvcConfigurer {
 
    /**
     * 允许跨域请求
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedMethods("*");
    }
 
}

同时也需要在WebSecurityConfigurerAdapter中开启跨域

@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
 
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable();
        ...
    }
 
}

原因:

虽然我们在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的跨域请求。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值