Spring Security 5,资源上没有“Access Control Allow Origin”头部。

huangapple go评论88阅读模式
英文:

Spring Security 5, No "Access Control Allow Origin" Header present on resource

问题

我有以下实现了WebMvcConfigurer接口并重写addCorsMappings方法的配置类(如此处描述:https://www.baeldung.com/spring-cors)

@Configuration
//@EnableWebMvc <- 我尝试过有和没有,没有效果
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请求到授权终端时,我会收到以下错误:

跨源资源共享(CORS)策略已阻止从源'http://localhost:3000'到' http://localhost:8080/auth?username=Example&password=Example' 的XMLHttpRequest。请求的资源上没有'Access-Control-Allow-Origin' 标头。

由于这种方法没有效果,我还尝试了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        : 在附加的过滤器链中位于位置3的15处,正在处理过滤器:'HeaderWriterFilter'
2020-05-29 13:52:40.378 DEBUG 21056 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy        : 在附加的过滤器链中位于位置4的15处,正在处理过滤器:'CsrfFilter'
2020-05-29 13:52:40.381 DEBUG 21056 --- [nio-8080-exec-1] o.s.security.web.csrf.CsrfFilter         : 在http://localhost:8080/auth?username=Example&password=Example上找到无效的CSRF令牌
2020-05-29 13:52:40.382 DEBUG 21056 --- [nio-8080-exec-1] o.s.s.w.header.writers.HstsHeaderWriter  : 未注入HSTS标头,因为它与org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@4ea0d6af的requestMatcher不匹配
2020-05-29 13:52:40.382 DEBUG 21056 --- [nio-8080-exec-1] w.c.HttpSessionSecurityContextRepository : SecurityContext为空或内容为匿名 - 不会将上下文存储在HttpSession中。

我尝试了各种建议的解决方案和用于旧Spring Security版本的CORS配置,但迄今为止,它们都没有对我的问题产生任何影响。

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

https://stackoverflow.com/questions/51802102/spring-boot-security-no-access-control-allow-origin-header-is-present-on-the-r#answer-51802163

编辑
我尝试使用了Firefox的CORS禁用扩展(以及其他各种HTTP客户端),但我没有看到任何区别,除了被重定向到/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");
        }
    };
}
英文:

I have the following Configuration Class that implements the WebMvcConfigurer Interface and Overrides the addCorsMappings method. (as described here: 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("/**");
    }
}

I also have a Configuration Class extending the 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);
    }
}

Whenever I make an HTTP request to my authorization endpoint, using Ajax, I get the following error:

Access to XMLHttpRequest at 'http://localhost:8080/auth?username=Example&password=Example' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Since this approach had no effect, I also tried the approach found in the Spring Security 5 documentation, but that also did not work:

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

I am not sure if this is due to my CORS configuration or some CSRF configuration (as far as I am concerned CSRF should be disabled due to my HttpSecurity config):

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.

I have tried various other suggested solutions and CORS configurations for older Spring Security versions but none of them has had any effect on my issue so far.

This seems like the most recent Solution for a similar question, also didn't work for me:

https://stackoverflow.com/questions/51802102/spring-boot-security-no-access-control-allow-origin-header-is-present-on-the-r#answer-51802163

EDIT:
I tried using a CORS disabling extension for Firefox (and various HTTP clients), but I was not able to see any differences apart from being redirected to the /login endpoint, which I also tried to disable using:

  http.httpBasic().disable()

My Spring Application still throws the same error as mentioned above in all of the test cases.

EDIT #2:
I also tried:

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

答案1

得分: 0

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

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

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

另外,您还可以使用此处指定的第二个选项

英文:

I think it doesn't work because you didn't add your origin(localhost:3000) to allowed origins. So Spring doesn't know which origins have access.

Spring guide shows how to do that :

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

Also you can use second option specified here

答案2

得分: 0

显然,应用程序在整个过程中都在使用默认配置,这导致我的安全配置没有任何效果,因此出现了CSRF/Cors问题。

问题的原因是我的应用程序类中错误地放置了@ComponentScan注解。

有@ComponentScan注解的情况:

2020-06-08 11:28:20.764 DEBUG 5612 --- [           main] s.s.c.a.w.c.WebSecurityConfigurerAdapter : 正在使用默认的configure(HttpSecurity)。如果被子类继承,这可能会覆盖子类的configure(HttpSecurity)。
2020-06-08 11:28:20.787 DEBUG 5612 --- [           main] FilterInvocationSecurityMetadataSource : 为任何请求添加网络访问控制表达式 'authenticated'
2020-06-08 11:28:20.790 DEBUG 5612 --- [           main] o.s.s.w.a.i.FilterSecurityInterceptor    : 验证配置属性
2020-06-08 11:28:20.791 DEBUG 5612 --- [           main] o.s.s.w.a.i.FilterSecurityInterceptor    : 验证配置属性

没有@ComponentScan注解的情况:

2020-06-08 11:34:56.343 DEBUG 8504 --- [           main] FilterInvocationSecurityMetadataSource : 为Ant [pattern='/user/signup*']添加网络访问控制表达式 'permitAll'
2020-06-08 11:34:56.344 DEBUG 8504 --- [           main] FilterInvocationSecurityMetadataSource : 为Ant [pattern='/auth*']添加网络访问控制表达式 'permitAll'
2020-06-08 11:34:56.344 DEBUG 8504 --- [           main] FilterInvocationSecurityMetadataSource : 为Ant [pattern='/nummern/**']添加网络访问控制表达式 'permitAll'
2020-06-08 11:34:56.344 DEBUG 8504 --- [           main] FilterInvocationSecurityMetadataSource : 为Ant [pattern='/information/']添加网络访问控制表达式 'hasRole('ROLE_OWNER')'
2020-06-08 11:34:56.345 DEBUG 8504 --- [           main] FilterInvocationSecurityMetadataSource : 为任何请求添加网络访问控制表达式 'authenticated'
英文:

Apparently the Application was using the default configuration the entire time, which caused none of my Security Configurations to have any effect and hence the CSRF/Cors issues.

The cause was a falsely placed @ComponentScan annotation in my Application class.

With Component Scan:

2020-06-08 11:28:20.764 DEBUG 5612 --- [           main] s.s.c.a.w.c.WebSecurityConfigurerAdapter : Using default configure(HttpSecurity). If subclassed this will potentially override subclass configure(HttpSecurity).
2020-06-08 11:28:20.787 DEBUG 5612 --- [           main] edFilterInvocationSecurityMetadataSource : Adding web access control expression 'authenticated', for any request
2020-06-08 11:28:20.790 DEBUG 5612 --- [           main] o.s.s.w.a.i.FilterSecurityInterceptor    : Validated configuration attributes
2020-06-08 11:28:20.791 DEBUG 5612 --- [           main] o.s.s.w.a.i.FilterSecurityInterceptor    : Validated configuration attributes

Without:

2020-06-08 11:34:56.343 DEBUG 8504 --- [           main] edFilterInvocationSecurityMetadataSource : Adding web access control expression 'permitAll', for Ant [pattern='/user/signup*']
2020-06-08 11:34:56.344 DEBUG 8504 --- [           main] edFilterInvocationSecurityMetadataSource : Adding web access control expression 'permitAll', for Ant [pattern='/auth*']
2020-06-08 11:34:56.344 DEBUG 8504 --- [           main] edFilterInvocationSecurityMetadataSource : Adding web access control expression 'permitAll', for Ant [pattern='/nummern/**']
2020-06-08 11:34:56.344 DEBUG 8504 --- [           main] edFilterInvocationSecurityMetadataSource : Adding web access control expression 'hasRole('ROLE_OWNER')', for Ant [pattern='/information/']
2020-06-08 11:34:56.345 DEBUG 8504 --- [           main] edFilterInvocationSecurityMetadataSource : Adding web access control expression 'authenticated', for any request

huangapple
  • 本文由 发表于 2020年5月29日 20:42:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/62086296.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定