虽然自动生成的表单登录页可以方便、快速地启动,但是大多数应用程序更希望提供自己的表单登录页,此时就需要覆写configure方法。
1.覆写configure方法,添加自定义配置
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/myLogin.html")
.permitAll() // 使登录页不设限访问
.and()
.csrf().disable();
}
}
2. 认识HttpSecurity
HttpSecurity实际上对应了Spring Security命名空间配置方式中XML文件内的标签,允许我们为特定的HTTP请求配置安全策略。
HttpSecurity提供了很多配置相关的方法,分别对应命名空间配置中的子标签<http>。例如,authorizeRequests()、formLogin()、httpBasic()和 csrf()分别对应<intercept-url>、<form- login>、<http-basic>和<csrf>标签。调用这些方法之后,除非使用and()方法结束当前标签,上下文才会回到HttpSecurity,否则链式调用的上下文将自动进入对应标签域。
authorizeRequests()方法实际上返回了一个URL拦截注册器,我们可以调用它提供的 anyanyRequest()、antMatchers()和regexMatchers()等方法来匹配系统的URL,并为其指定安全策略。