Spring 通过 Angular 启动授权服务器访问 - 不断出现 CORS 错误

Spring boot Authorisation server access by Angular - keeps on giving CORS errors

使用 "ng serve" 我启动了一个 Angular 应用程序。 Angular 应用程序使用 post 在 Spring 启动(授权)服务器上获得授权。

无论我尝试什么,我都会不断收到这样的回复:

OPTIONS http://localhost:9999/oauth/authorize 404 () Failed to load http://localhost:9999/oauth/authorize: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 404.

更新:我会把这个 post 留在网上,因为它可以帮助你一步步解决 CORS(跨源)错误。

我尝试了很多方法来让 Spring 引导应用程序启用 CORS。

选项1:在WebMvcConfigurerAdapter中添加CorsMappings。

@SpringBootApplication
@Controller
@SessionAttributes("authorizationRequest")
@EnableWebSecurity
@EnableAuthorizationServer
public class AuthserverApplication extends WebMvcConfigurerAdapter {
   ... 
   @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }

一个变体是当你还没有 WebMvcConfigurerAdapter class 时。将此添加到您的 Spring 启动应用程序。另见@Maj 的回答。

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurerAdapter() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**");
        }
    };
}

当然你可以启用更细粒度的Cors。

选项 2: 将 cors() 添加到您的 WebSecurity 适配器中

@Configuration
@Order(-20)
protected static class LoginConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .cors()
        .and()
            .formLogin().loginPage("/login").permitAll()
        etc. 
            .csrf().disable();
    }

选项 3:将 corsBean() 添加到您的安全适配器。

@Bean
CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();              
    configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
 configuration.setAllowedMethods(Arrays.asList("GET","OPTIONS","PUT","POST"));
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

选项 4: 向您的 AuthorizationServerConfigurerAdapter 添加过滤器 {

@Bean
public FilterRegistrationBean corsFilterRegistrationBean() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("*");
    config.addAllowedHeader("*");
    config.addAllowedMethod("*");
    source.registerCorsConfiguration("/**", config);
    FilterRegistrationBean bean = new FilterRegistrationBean(
         new CorsFilter(source));
    bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
    return bean;
}

选项 5: 添加自定义 cors 过滤器

public class WebSecurityCorsFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse res = (HttpServletResponse) response;
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
        res.setHeader("Access-Control-Max-Age", "3600");
        res.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type, Accept, x-requested-with, Cache-Control");
        chain.doFilter(request, res);
    }
    @Override
    public void destroy() {
    }
}

在网络安全配置器中:

@Bean
WebSecurityCorsFilter myCorsFilter() {
    return new WebSecurityCorsFilter();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .addFilterBefore(myCorsFilter(), 
                           SessionManagementFilter.class)
        .cors()
        .and()
            .formLogin().etc.

选项 6:删除安全性。将 Spring 引导应用程序减少到最低限度。只是为了做出更好的诊断。将 corsMapping() 添加到 Spring 引导应用程序 class。

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurerAdapter() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**").allowedOrigins("*");
        }
    };
}

public static void main(String[] args) {
    SpringApplication.run(AuthserverApplication.class, args);
}

选项 7: Chrome 这方面有一个错误。因此,我尝试以全新的方式使用 Firefox。

选项 8:将 Spring 启动应用程序转换为 Web 应用程序。 没有。没有不同。

选项 9:控制器路径错误?

这真的是 CORS 错误还是指示错误的 REST 路径的错误?

错误消息表明,在我的例子中,这是一个 CORS 错误。但最后,我被示例代码中引入 context.path 的方式给骗了。

我有一个类似的问题,我的 angular 应用程序无法访问我的 spring 启动和

我在我的安全配置中添加了这个方法:

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurerAdapter() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("http://localhost:" + port") // angular port here
                    .allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH");
        }
    };
}

但是我后来转而使用 Electron 应用程序,不得不放弃安全性,但我认为您绝对需要 cors

检查了题中的所有选项后,终于找到了问题所在。

将 Spring 启动应用程序剥离到最低限度后,我诊断出错误。

错误表明这是一个 CORS 错误。但是,事实并非如此。我被这个例子中 context.path 的使用方式所欺骗。

所以,它看起来像一个 CORS 错误,但它是一个 WRONG PATH 错误。