如果您尝试通过 REST 端点接收用户凭据并手动验证用户身份,您可以这样做:
@RestController
@RequestMapping("/login")
public class LoginController {
private final AuthenticationManager authenticationManager;
// constructor injecting authenticationManager
@PostMapping
public void login(@RequestBody UserCredentials credentials) {
UsernamePasswordAuthenticationToken token
= new UsernamePasswordAuthenticationToken(credentials.getUsername(), credentials.getPassword());
Authentication auth = this.authenticationManager.authenticate(token);
if (auth != null) {
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(auth);
SecurityContextHolder.setContext(context);
}
throw new SomeException();
}
}
这样,Filters
它将为您处理其余的身份验证步骤。可以研究 Spring Security 文档以获取更多详细信息。
如果您想使用默认登录页面生成的端点,您可以按照文档中的步骤提出您自己的请求:
- 表单应该执行到 /login 的帖子
- 该表格需要包含一个由 Thymeleaf 自动包含的 CSRF 令牌。
- 表单应在名为 username 的参数中指定用户名
- 表单应在名为 password 的参数中指定密码
- 如果发现HTTP参数错误,说明用户未能提供有效的用户名/密码
- 如果找到http参数logout,说明用户已经注销成功