Spring Security / j_spring_security_check未找到404


问题内容

这是我的WebAppInitializer:

@Configuration
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[] { AppConfig.class, WebSecurityConfig.class };
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[] { WebConfig.class };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }
}

这是我的安全配置:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/resources/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http.authorizeRequests()
                .antMatchers("/signup", "/about").permitAll()
                .antMatchers("/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated()
                .and().formLogin().loginPage("/login").defaultSuccessUrl("/home").failureUrl("/error").permitAll()
                .and().httpBasic();
        // @formatter:on
    }

}

这是我的login.html(来自百里香的html示例):

<form th:action="@{/j_spring_security_check}" method="post">
  <label for="j_username">Username</label>:
  <input type="text" id="j_username" name="j_username" /> <br />

  <label for="j_password">Password</label>:
  <input type="password" id="j_password" name="j_password" /> <br />

  <input type="submit" value="Log in" />
</form>

当我单击登录时,出现此错误:

HTTP ERROR 404

Problem accessing /j_spring_security_check. Reason:

    Not Found

我如何摆脱这个错误?我用谷歌搜索了很多,但是还没有成功。(是的,我不使用任何xml。)


问题答案:

我已经创建了它,现在可以使用:

import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;

public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {

}

这将相应地激活SpringSecurityFilterChain。

由于CSRF错误,我还必须从@EnableWebSecurity切换到 @EnableWebMvcSecurity 。如spring文档中所写:

…原因是Spring
Security可以防止CSRF攻击,并且我们的请求中没有CSRF令牌。更新我们的配置以使用@EnableWebMvcSecurity批注,该批注与@EnableWebMvcSecurity相同,并提供与Spring
MVC的集成。除其他事项外,它将确保使用Thymleaf 2.1+或Spring MVC标签库时,我们的CSRF令牌自动包含在我们的表单中…

也感谢Deinum M.的评论。Spring最近已将/ j_spring_security_check / j_password /
j_username显然切换为/ login / password / username。