我正在尝试了解 Spring Security,我遇到了这个问题,我想创建一个自定义的登录 html,但我似乎无法处理它。
@Configuration
@EnableWebSecurity
public class SecurityConfig {
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.formLogin(form -> form
.loginPage("/login")
.permitAll()
);
return http.build();
}
}
@Controller
class LoginController {
@GetMapping("/login")
String login() {
return "login";
}
}
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org">
<head>
<title>Please Log In</title>
</head>
<body>
<h1>Please Log In</h1>
<div th:if="${param.error}">
Invalid username and password.</div>
<div th:if="${param.logout}">
You have been logged out.</div>
<form th:action="@{/login}" method="post">
<div>
<input type="text" name="username" placeholder="Username"/>
</div>
<div>
<input type="password" name="password" placeholder="Password"/>
</div>
<input type="submit" value="Log in" />
</form>
</body>
</html>
我尝试了以下官方 Spring 网站,我从那里做了所有事情,但是当我将其托管在本地主机上并尝试访问 /login 时,它显示了 Spring 默认登录页面而不是我定制的页面
不幸的是,Spring 文档有时有点断章取义,假设每个人都知道要采取的额外步骤,这并不总是很方便,特别是对于新手来说。要运行示例,您需要将
@Bean
应用于 SecurityFilterChain
,以便 Spring Boot 来拾取它:
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.formLogin(form -> form
.loginPage("/login")
.permitAll()
);
return http.build();
}
}