记录一下 springboot 整合 SecurityConfig后, 前端访问后端跨域的坑

一、WebMvcConfigurer 中添加跨域配置

注意: addExposedHeader() 一定要配置, 否则前端将获取不到响应头中的 TOKEN /Authorization 参数

@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);
    }
}

二、SecurityConfig中的配置修改

添加一

配置允许跨域访问 ,不要加 .disable(); ,否则一样无法访问

http.cors();    //.disable();

添加二

     // 当出现跨域的OPTIONS请求时,发现被拦截,加入下面设置可实现对OPTIONS请求的放行。
    http.authorizeRequests().
           requestMatchers(CorsUtils::isPreFlightRequest).
           permitAll();
    }

当前完整授权代码如下

    /**
     *  授权
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
    
    

        // 只拦截需要拦截的所有接口, 拦截数据库权限表中的所有接口
        List<AdminAuthority> authoritys = adminAuthorityMapper.selectList(null);
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry eiur = http.authorizeRequests();
        authoritys.forEach((auth) -> {
            eiur.antMatchers(auth.getUrl()).hasAnyAuthority(auth.getUrl());
        });
        // 配置token验证及登录认证,过滤器
        eiur
                // 登录接口不需要权限控制,可删除,目前该接口不在权限列表中
                .antMatchers("/auth/login", "POST").permitAll()
                // 设置JWT过滤器
                .and()
                .addFilter(new JWTValidFilter(authenticationManager(), resolver))
                .addFilter(new JWTLoginFilter(authenticationManager(), resolver)).csrf().disable()
                // 剔除session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        // 开启跨域访问
        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();
    }

个人开源项目(通用后台管理系统)–> https://gitee.com/wslxm/spring-boot-plus2 , 喜欢的可以看看
本文到此结束,如果觉得有用,动动小手点赞或关注一下呗,将不定时持续更新更多的内容…,感谢大家的观看!

猜你喜欢

转载自blog.csdn.net/qq_41463655/article/details/108038756