java - Spring Security 5,资源上没有 "Access Control Allow Origin" header

标签 java spring spring-boot

我有以下配置类,它实现 WebMvcConfigurer 接口(interface)并重写 addCorsMappings 方法。 (如下所述:https://www.baeldung.com/spring-cors)

@Configuration
//@EnableWebMvc <- I tried with and without, no effect
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }
}

我还有一个扩展 WebSecurityConfigurerAdapter 的配置类:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomUserDetailsService customService = new CustomUserDetailsService();


    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http            
            .cors().and()
            .csrf().disable()
            .authorizeRequests()
            .antMatchers("/user/signup*").permitAll()
            .and()
            .authorizeRequests()
            .antMatchers("/auth*").permitAll()
            .and()
            .authorizeRequests()
            .antMatchers("/nummern/**").permitAll()
            .and()
            .authorizeRequests()
            .antMatchers("/information/").hasRole("OWNER")
            .and()
            .authorizeRequests()
            .anyRequest().authenticated()
            .and()
            .addFilter(new JwtAuthenticationFilter(authenticationManager()))
            .addFilter(new JwtAuthorizationFilter(authenticationManager()))
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
}

每当我使用 Ajax 向授权端点发出 HTTP 请求时,都会收到以下错误:

访问位于“http://localhost:8080/auth?username=Example&password=Example”的 XMLHttpRequest '来自原点'http://localhost:3000 ' 已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin” header 。

由于这种方法没有效果,我也尝试了Spring Security 5文档中的方法,但也不起作用:

https://docs.spring.io/spring-security/site/docs/5.0.5.RELEASE/reference/htmlsingle/#cors

我不确定这是否是由于我的 CORS 配置或某些 CSRF 配置造成的(据我所知,由于我的 HttpSecurity 配置,CSRF 应该被禁用):

2020-05-29 13:52:40.377 DEBUG 21056 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy        : /auth?username=Example&password=Example at position 3 of 15 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2020-05-29 13:52:40.378 DEBUG 21056 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy        : /auth?username=Example&password=Example at position 4 of 15 in additional filter chain; firing Filter: 'CsrfFilter'
2020-05-29 13:52:40.381 DEBUG 21056 --- [nio-8080-exec-1] o.s.security.web.csrf.CsrfFilter         : Invalid CSRF token found for http://localhost:8080/auth?username=Example&password=Example
2020-05-29 13:52:40.382 DEBUG 21056 --- [nio-8080-exec-1] o.s.s.w.header.writers.HstsHeaderWriter  : Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@4ea0d6af
2020-05-29 13:52:40.382 DEBUG 21056 --- [nio-8080-exec-1] w.c.HttpSessionSecurityContextRepository : SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.

我已经针对较旧的 Spring Security 版本尝试了各种其他建议的解决方案和 CORS 配置,但到目前为止,它们都没有对我的问题产生任何影响。

这似乎是类似问题的最新解决方案,但对我来说也不起作用:

Spring Boot Security No 'Access-Control-Allow-Origin' header is present on the requested resource Error

编辑: 我尝试使用 Firefox(和各种 HTTP 客户端)的 CORS 禁用扩展,但除了重定向到/login 端点之外,我看不到任何差异,我也尝试使用以下方法禁用该扩展:

  http.httpBasic().disable()

我的 Spring 应用程序在所有测试用例中仍然抛出与上面提到的相同的错误。

编辑#2: 我也尝试过:

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

最佳答案

我认为它不起作用,因为您没有将您的来源(localhost:3000)添加到允许的来源。所以 Spring 不知道哪些来源可以访问。

Spring guide展示了如何做到这一点:

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/greeting-javaconfig").allowedOrigins("http://localhost:9000");
        }
    };
}

您也可以使用second option specified here

关于java - Spring Security 5,资源上没有 "Access Control Allow Origin" header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62086296/

相关文章:

java - Mapstruct - 在响应中发送具有(一对多关系)的嵌套实体

java - Android Studio 是否有 NonNullByDefault 注解

java - 在真实mysql系统中处理DELETE的最佳方法

java - 如何使用 Spring Actuator 在浏览器屏幕中显示日志文件的内容?

java - Spring Security with session get online users 返回空

java - 当我将其部署在 openshift 上时,我的 WEB 应用程序中的搜索仅适用于拉丁符号,但它在我的本地计算机上运行良好

java - 使用正则表达式拆分字符串不返回任何值

java - 用户登录后如何重定向到目标页面

java - Spring Batch 适合我的服务代码吗?

java - 从 Java 使用表类型参数调用 OracleDB 过程——DB 总是接收空值而不是值