一。 自定义登录界面,需要先创建一个自己的登录界面(存放位置:在resources中建立目录resources,在这个目录中新建html文件用来登录),并在securtyConfig类中进行说明:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>我的登录页-demo</title>
</head>
<body>
<h2>标准登录信息</h2>
<h3>表单登录</h3>
<form action="/login" 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>
@EnableWebSecurity
public class SecurtyConfig extends WebSecurityConfigurerAdapter {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
/**
* 自定义配置
*
* @param http
* @throws Exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin() //基于Form表单登录验证
.loginPage("/mylogin.html") //自定义登录页
.loginProcessingUrl("/login") //表单提交相匹配,否则无法登录
.and()
.authorizeRequests()
.antMatchers("/mylogin.html").permitAll() //防止登录页也需要进行登录验证,添加这个说明登录页不进行验证
.anyRequest()
.authenticated();
}
添加后,发现还是不能正常运行,是因为spring security自动包含跨站伪造防护功能,我们需要先进行关闭;
protected void configure(HttpSecurity http) throws Exception {
http.formLogin() //基于Form表单登录验证
.loginPage("/mylogin.html") //自定义登录页
.loginProcessingUrl("/login") //表单提交相匹配,否则无法登录
.and()
.authorizeRequests()
.antMatchers("/mylogin.html").permitAll() //防止登录页也需要进行登录验证,添加这个说明登录页不进行验证
.anyRequest()
.authenticated()
.and()
.csrf().disable(); // 关闭spring security的跨站伪造防护功能
}