加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

javascript – CORS干扰Spring Security oauth2

发布时间:2020-12-15 01:40:01 所属栏目:大数据 来源:网络整理
导读:我在尝试从浏览器中获取来自oauth / token的令牌时遇到问题.我有一个带有Spring Security和Spring Security oauth的Spring Boot应用程序,我正在尝试从另一个端口的javascript SPA进行身份验证. 当在后端禁用CORS时,我可以使用Postman或终端从oauth端点获取令

我在尝试从浏览器中获取来自oauth / token的令牌时遇到问题.我有一个带有Spring Security和Spring Security oauth的Spring Boot应用程序,我正在尝试从另一个端口的javascript SPA进行身份验证.

当在后端禁用CORS时,我可以使用Postman或终端从oauth端点获取令牌没问题,但是由于CORS预检失败,我无法从javascript获取它们.

如果我启用了CORS,则预检成功,但现在我收到InsufficientAuthenticationException,说“没有客户端身份验证.尝试添加适当的身份验证过滤器”.从我可以收集的内容来看,这是因为Spring Security无法从请求中获取主体.

有没有人有关于如何处理这个问题的建议?

最佳答案
因此,在阅读了一半的互联网之后,我得到了一个解决方案……显然Oauth2端点和过滤器在进入Spring Security过滤器链之前得到了处理,因此添加CORS过滤器通常不起作用……但添加了一个CORS过滤器高优先级的bean最终工作.
这是我对CORS的专用配置类(改编自官方春季指南,我稍后会调整它)

@Configuration
public class CorsConfig {
//IMPORTANT: it has to be a normal configuration class,//not extending WebMvcConfigurerAdapter or other Spring Security class
    @Bean
    public FilterRegistrationBean customCorsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("http://localhost:3000");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**",config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));

        //IMPORTANT #2: I didn't stress enough the importance of this line in my original answer,//but it's here where we tell Spring to load this filter at the right point in the chain
        //(with an order of precedence higher than oauth2's filters)
        bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
        return bean;
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读