相关文章:
Spring Security默认登录页面原理
spring security 自定义登录页面
1. 自定义登录页面
核心是通过配置,覆盖原有默认的登陆页面:
//不写这个注解配置不生效
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin()
.loginPage("/demo-login.html")
.loginProcessingUrl("/demo-login");
}
}
注意:loginPage和loginProcessingUrl参数必须同时成对出现,否则会有问题
这时,需要你新增一个demo-login.html页面
此外,为了避免重定向死循环现象:
这时候发现浏览器提示了重定向的次数过多
错误,这是为啥呢?我们来分析一下我们在浏览器地址栏里面输入我们接口地址按下回车之后都发生了啥。
访问/hello接口,因为我们刚才配置了所有请求都需要身份认证,现在我们没有登录那自然就要跳转到登录页登录,跳转/demo-login.html。可是/demo-login.html也需要身份认证啊,那就再次跳转/demo-login.html,这样重复往返就死循环下去了。
问题讲清楚之后,那解决方案就很明确了,把/demo-login.html和/demo-login(form表单action属性的值)配置为不需要认证,放行。
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin()
.loginPage("/demo-login.html")
.loginProcessingUrl("/demo-login")
.and()
.authorizeRequests()
.antMatchers("/demo-login.html", "/demo-login").permitAll() //对于登陆页面,要让所有人免密登陆,否则,会进不去登陆页面,产生重定向死循环
.anyRequest().authenticated();
}
}
2. 关闭csrf token
默认情况下开启csrf token,会导致我们上面运行仍然失败:
我们发现报错了,显示无效的csrf token。这是因为spring security默认开启了csrf防护,只要在请求中带上csrf token就可以了。这个token在返回登录页面的时候spring security已经帮我们准备好了,只是我们没有使用模板引擎,所以取到token比较困难,这里我们把csrf关闭吧,大家可以自己摸索一下如何取到这个token,带上就完事了。重写一下配置。
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin()
.loginPage("/demo-login.html")
.loginProcessingUrl("/demo-login")
.and()
.authorizeRequests()
.antMatchers("/demo-login.html", "/demo-login").permitAll()
.anyRequest().authenticated()
.and()
.csrf().disable(); //先关闭,将来在说
}
}