SpringBoot 集成 SpringSecurity 详解(七)-- 自定义登录页面
需求缘起
系统默认的登录页面不友好,这一节我们来实现自定义登录页面。
本节是在第六小节的基础上继续开发。
本节 demo
技术要点
- 编写登录界面
- 配置页面和登录路径等
1.编辑登录界面
编写login.html界面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<h2>自定义登录页面</h2>
<form action="/authentication/form" method="post">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td colspan="2">
<button type="submit">登录</button>
</td>
</tr>
</table>
</form>
</body>
</html>
2.配置Spring Security的登录页面路径
@Configuration
@EnableWebSecurity//开启Spring Security的功能
@EnableGlobalMethodSecurity(prePostEnabled = true)//开启方法安全级别的控制
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public PasswordEncoder passwordEncoder() {
//SpringSecurity 提供的一种编码器,我们也可以自己实现PasswordEncoder
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// super.configure(http);
http.formLogin()
.loginPage("/login.html")// 自定义登录页面路径
.loginProcessingUrl("/authentication/form")// 自定义页面的登录路径,注意要与登录页面的action值一致,<form action="/authentication/form" method="post">
.and()
.authorizeRequests() // 定义哪些URL需要被保护、哪些不需要被保护
.antMatchers("/login.html").permitAll()// 设置所有人都可以访问登录页面
.anyRequest().authenticated() // 除了以上的请求外都需要身份验证
;
http.csrf().disable();// 禁用跨站攻击
}
}
3.测试
重启应用,访问http://localhost:8080/hello/helloUser
现在的界面已经变成了我们自定义的界面,如下所示
然后输入用户名密码即可访问。
提示:
- login.html 要放在resource/static 目录下;
- 配置的 loginProcessingUrl 参数中的值要与界面中action中的值一致。