CORS干扰Spring Security oauth2

SrT*_*son 6 javascript java spring spring-security oauth-2.0

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

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

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

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

SrT*_*son 20

因此,在阅读了一半的互联网之后,我得到了一个解决方案......显然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;
    }
}
Run Code Online (Sandbox Code Playgroud)