javascript–CORS干扰Spring Security oauth2

javascript–CORS干扰Spring Security oauth2,第1张

概述我在尝试从浏览器中获取来自oauth / token的令牌时遇到问题.我有一个带有Spring Security和Spring Security oauth的Spring Boot应用程序,我正在尝试从另一个端口的javascript SPA进行身份验证.当在后端禁用CORS时,我可以使用Postman或终端从oauth端点获取令牌没问题,但是由于CORS预

我在尝试从浏览器中获取来自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的专用配置类(改编自官方春季指南,我稍后会调整它)

@Configurationpublic 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;    }}
总结

以上是内存溢出为你收集整理的javascript – CORS干扰Spring Security oauth2全部内容,希望文章能够帮你解决javascript – CORS干扰Spring Security oauth2所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1265846.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-08
下一篇2022-06-08

发表评论

登录后才能评论

评论列表(0条)

    保存