代码之家  ›  专栏  ›  技术社区  ›  tm1701

Angular访问Spring boot授权服务器-不断提供CORS错误

  •  -1
  • tm1701  · 技术社区  · 7 年前

    使用“ng serve”我启动一个角度应用程序。Angular应用程序使用post在Spring Boot(授权)服务器上获取授权。

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

    选项 http://localhost:9999/oauth/authorize 404()加载失败 http://localhost:9999/oauth/authorize :对飞行前请求的响应 未通过访问控制检查:无“访问控制允许源站” 请求的资源上存在标头。起源 ' http://localhost:4200 因此不允许访问。回应 具有HTTP状态代码404。

    更新:我将把这篇文章留在网上,因为它可以帮助你一步一步地解决CORS(跨源)错误。

    我尝试了许多方法来允许Spring Boot应用程序启用CORS。

    选项1 :在WebMVCConfigureAdapter中添加Corsmappings。

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

    这方面的一个变体是当您还没有WebMVCConfigureAdapter类时。将其添加到Spring Boot应用程序中。另请参见@Maj.的答案。

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

    当然,您可以更细粒度地启用Cors。

    选项2: 将cors()添加到您的Web安全适配器“

    @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() {
        }
    }
    

    在WebSecurity配置器中:

    @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 Boot应用程序减少到最低限度。只是为了更好的诊断。将corsMapping()添加到Spring Boot应用程序类。

    @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中有一个bug。因此,我尝试以一个干净的开始使用Firefox。

    选项8 :将Spring Boot应用程序转换为web应用程序。 不。没有区别。

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

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

    在我的例子中,错误消息表明这是一个CORS错误。但最后,我被上下文的方式欺骗了。示例代码中引入了路径。

    2 回复  |  直到 7 年前
        1
  •  0
  •   tm1701    7 年前

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

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

    该错误表明这是CORS错误。但是,事实并非如此。我被上下文的方式所欺骗。本例中使用了路径。

    所以,它看起来像一个CORS错误,但它是一个错误的路径错误。

        2
  •  -1
  •   Maj    7 年前

    我有一个类似的问题,我的angular应用程序无法访问我的spring boot backand

    我在安全配置中添加了此方法:

    @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