前后端分离跨域请求,发起两次请求,第一次Options导致Access is denied的问题

  • 前言

如标题所示的问题,一直以为是简单的跨域问题造成的,但是发现前端GET、POST、DELETE请求都是带了token的,而且都是可以请求到数据的,一直通过度娘找了很久,也追踪了很久的源码,都无所收获。

  • 解决

​​​​​​​经过某位博主的指引,发现需要加上对Options的请求进行放行

@Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                // 由于使用的是JWT,我们这里不需要csrf
                .csrf().disable().authorizeRequests()
                // 基于token,所以不需要session
                // 1.先配置放行不需要认证的 permitAll()
                .requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
                //对请求进行认证  url认证配置顺序为:
                // 2.然后配置 需要特定权限的 hasRole()
                // 3.最后配置 anyRequest().authenticated()
                .and().authorizeRequests()
                .antMatchers(ignoredAuths.split(",")).permitAll()
                .anyRequest().authenticated()
                .and().exceptionHandling()
                //认证失败
                .authenticationEntryPoint(entryPointUnauthorizedHandler)
                //用户已经通过了登录认证,在访问一个受保护的资源,但是权限不够
                .accessDeniedHandler(myAccessDeniedHandler)
                .and().headers().cacheControl();
        //在 beforeFilter 之前添加 自定义 filter
        httpSecurity.addFilterBefore(myFilterSecurityInterceptor, FilterSecurityInterceptor.class);
        httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

也就是很重要的一句话

然后你会发现一切都OJ8K了... 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值