栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Spring Boot CORS过滤器-CORS预检通道未成功

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring Boot CORS过滤器-CORS预检通道未成功

我已经通过创建新的CORS过滤器解决了此问题:

@Componentpublic class CorsFilter extends oncePerRequestFilter {    @Override    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {        response.setHeader("Access-Control-Allow-Origin", "*");        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");        response.setHeader("Access-Control-Max-Age", "3600");        response.setHeader("Access-Control-Allow-Headers", "authorization, content-type, xsrf-token");        response.addHeader("Access-Control-Expose-Headers", "xsrf-token");        if ("OPTIONS".equals(request.getMethod())) { response.setStatus(HttpServletResponse.SC_OK);        } else {  filterChain.doFilter(request, response);        }    }}

并将其添加到安全配置中:

.addFilterBefore(new CorsFilter(), ChannelProcessingFilter.class)

更新-如今,我使用了更现代的方式切换到:

@Configuration@EnableWebSecuritypublic class WebSecurityConfig extends WebSecurityConfigurerAdapter {    @Override    protected void configure(HttpSecurity http) throws Exception {        http .cors()        .and()        ...    }    @Bean    public CorsConfigurationSource corsConfigurationSource() {        CorsConfiguration configuration = new CorsConfiguration();        configuration.setAllowedOrigins(Arrays.asList("*"));        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));        configuration.setAllowedHeaders(Arrays.asList("authorization", "content-type", "x-auth-token"));        configuration.setExposedHeaders(Arrays.asList("x-auth-token"));        UrlbasedCorsConfigurationSource source = new UrlbasedCorsConfigurationSource();        source.registerCorsConfiguration("/**", configuration);        return source;    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/407855.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号