CSRF Token ‘null‘ 报错解决方案

Spring Security CSRF,默认是开启。CSRF默认支持的方法: GET|HEAD|TRACE|OPTIONS,不支持POST。

1关闭方案

@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.inMemoryAuthentication().withUser("test").password("test").roles("USER").
			and().withUser("admin").password("admin").roles("USER","ADMIN");
	    }
	
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests().antMatchers("/spittles/register").access("isAuthenticated()")
			.antMatchers("/spittles/register").access("isAuthenticated()")
		.antMatchers("/home").access("isAuthenticated()")
		.antMatchers("/spittles/toUpload").access("isAuthenticated()")
		.anyRequest().permitAll()
		.and().formLogin()
		.and().httpBasic();
		http.csrf().disable();//关闭CSRF
    }
}

2.配置控制

当然,也可以将excluded配置为/*来规避所有url,达到和关闭一样的效果。

spring.security.csrf.supportedMethods=POST,PUT,GET,DELETE,OPTIONS
spring.security.csrf.url.style=regex
spring.security.csrf.url.included=/.*?
spring.security.csrf.url.excluded=^/csrf/nocheck,/test/
经验分享 程序员 微信小程序 职场和发展