[!hint] 后续的步骤都是基于前后端分离的开发模式
前端
前端发送 POST 请求到 后端的 /login ,这个路径是 Spring Security 的过滤器自带的登录接口路径
- 定义前端页面,及其
<form> 表单
html
<!-- 指定登录路径,和请求方式 -->
<form action="http://localhost:8080/login" method="post">
<div class="row mb-2">
<div class="col-11 d-flex mx-auto">
<!-- input中的name属性的值一定要写username -->
<input name="username" type="text" class="form-control" placeholder="用户名" required>
</div>
</div>
<div class="row mb-2">
<div class="col-11 d-flex mx-auto">
<!-- input中的name属性的值一定要写password -->
<input name="password" type="text" class="form-control" placeholder="密码" required>
</div>
</div>
<button class="btn btn-primary d-block mx-auto" type="submit">登录</button>
</form>` 标签` 中的 name 属性必需要和 `UsernamePasswordAuthenticationFilter` 对应
java
private String usernameParameter = "username";
private String passwordParameter = "password";如果要修改这两个值,可以在自定义配置 SecurityConfig 中修改:
java
http
……
.formLogin(form -> {
form.loginPage("http://localhost:5173/")
// 修改
.usernameParameter("myusername")
.passwordParameter("mypassword");
});后端
- 修改默认配置,将登录页定向到前端页面
java
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(authorize -> authorize
.anyRequest()
.authenticated()
)
.formLogin(form -> {
// 将登录页定向到前端页面
form.loginPage("http://localhost:5173/")
// 指明前端登录页面需要请求后端的哪个路径
.loginProcessingUrl("/login");
});
return http.build();
}