多个WebSecurityJAVA配置导致csrf().disable()配置失效

版本

spring-security-oauth2-2.3.8

问题

存在两个继承WebSecurityConfigurerAdapter的WebSecurity JAVA配置文件,一个配置了http.csrf().disable(),一个没有配置,请求仍然报错Invalid CSRF token found

解决

合并WEBSECURITY配置,或两个文件都配置上http.csrf().disable()

分析

Spring源码WebSecurityConfigurerAdapter中http默认配置启用csrf,如果继承该类进行配置,需手动禁用
org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter

protected final HttpSecurity getHttp() throws Exception {
	if (http != null) {
		return http;
	}

	AuthenticationEventPublisher eventPublisher = getAuthenticationEventPublisher();
	localConfigureAuthenticationBldr.authenticationEventPublisher(eventPublisher);

	AuthenticationManager authenticationManager = authenticationManager();
	authenticationBuilder.parentAuthenticationManager(authenticationManager);
	Map<Class<?>, Object> sharedObjects = createSharedObjects();

	http = new HttpSecurity(objectPostProcessor, authenticationBuilder,
			sharedObjects);
	if (!disableDefaults) {
		// @formatter:off
		http
			.csrf().and()
			.addFilter(new WebAsyncManagerIntegrationFilter())
			.exceptionHandling().and()
			.headers().and()
			.sessionManagement().and()
			.securityContext().and()
			.requestCache().and()
			.anonymous().and()
			.servletApi().and()
			.apply(new DefaultLoginPageConfigurer<>()).and()
			.logout();
		// @formatter:on
		ClassLoader classLoader = this.context.getClassLoader();
		List<AbstractHttpConfigurer> defaultHttpConfigurers =
				SpringFactoriesLoader.loadFactories(AbstractHttpConfigurer.class, classLoader);

		for (AbstractHttpConfigurer configurer : defaultHttpConfigurers) {
			http.apply(configurer);
		}
	}
	configure(http);
	return http;
}

posted on 2022-04-11 22:38  路过君  阅读(10)  评论(0编辑  收藏  举报

导航