為了方便起見,我們在`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了。