使用Spring Security 4时遇到了一些问题

在Spring Security 4中,默认启用了CSRF保护。
当尝试进行身份验证时,将在屏幕上显示。

Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'

我一开始觉得很奇怪,但当我看了Stack Overflow和Spring Security 3到4的迁移指南后,上面写着。所以,我采取了以下的方法来绕过(禁用)它(顺便一提,我是用的Spring Boot)。

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/login").permitAll().anyRequest().authenticated();
        // ★http.csrf().disable()でCSRFを無効 
        http.csrf().disable().formLogin().loginProcessingUrl("/auth").loginPage("/login").failureUrl("/login?error")
                .defaultSuccessUrl("/top", true).usernameParameter("userId").passwordParameter("password");
    }
}

如果要发送令牌,请按照以下页面所示的方式设置令牌即可。 https://terasolunaorg.github.io/guideline/public_review/Security/CSRF.html

在Spring Security 4中,@EnableWebMvcSecurity已被弃用,取而代之的是使用@EnableWebSecurity。

Spring Security 4迁移指南
http://docs.spring.io/spring-security/site/migrate/current/3-to-4/html5/migrate-3-to-4-xml.html

顺便提一下背景,我正在阅读《初学Spring Boot》一书中关于Spring Security的章节。书中基本上使用的是Spring Boot 1.1.8.RELEASE版本,而此时的Spring Security版本是3.2.5.RELEASE。可我不知道怎么搞得,突然想要使用最新版本的Spring Boot,于是我指定了1.3.1.RELEASE版本,结果Spring Security变成了4版本,变成了这个样子。

广告
将在 10 秒后关闭
bannerAds