为了方便起见,我们在`resources/static`目录下创建一个`login.html`文件。
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<form action="/login" method="post">
<div>
<h3>账户登录</h3>
<input type="text" placeholder="用户名" name="username" required="required"/>
<input type="password" placeholder="密码" name="password" required="required"/>
<button type="submit">登录</button>
</div>
</form>
</body>
</html>
```
修改BrowserSecurityConfig配置
```java
@Configuration
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin() // 表单方式
.loginPage("/login.html") // 指定登录页
.loginProcessingUrl("/login") // 指定登录处理url
.and()
.authorizeRequests()
.antMatchers("/login.html").permitAll() // 放行/login.html
.anyRequest()
.authenticated();
}
}
```
访问http://www.zhangpn.com/hello。此时,还是访问不了的,因为我们需要关闭CSRF攻击防御。
```java
@Configuration
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin()
.loginPage("/login.html")
.loginProcessingUrl("/login")
.and()
.authorizeRequests()
.antMatchers("/login.html").permitAll()
.anyRequest()
.authenticated()
.and().csrf().disable(); // 关闭csrf
}
}
```
此时,访问http://www.zhangpn.com/hello。就OK了。
