环境说明:
- JDK:17
- Spring Boot: 3.4.0
- Spring Security: 6.4
0X00 概要
目标:
- 实现一个登录接口且配置该接口不需要认证;
- 实现 JWT 的认证;
- 自定义认证失败;
0x01 基础配置
密码编码格式的设置
// cn.keeploving.demo.config.SecurityConfig
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
实现 UserDetailsService,该接口仅有一个方法:loadUserByUsername,是根据登录的凭证(如:用户名、手机号、邮箱等)获取用信息的。
// cn.keeploving.demo.config.SecurityConfig
@Bean
public UserDetailsService userDetailsService(PasswordEncoder passwordEncoder) {
// 这里使用 memory的,也可以自己继承进行实现
// 这里就意味着有一个账号test,密码是 abc@123
return new InMemoryUserDetailsManager(
new User("test",
passwordEncoder.encode("abc@123"),
new ArrayList<>()
)
);
}
0x02 登录接口的实现
基本的登录接口的需要实现一下功能:
- 验证登录输入的验证码(如果有);
- 检查账号是否存在、密码是否正确,不存在(正确)则返回提示信息,如:用户名或密码错误;
- 检查账号的其他状态,返回对应的提示信息,如:账号已经锁定;
- 验证成功返回 JWT。
使用 Spring security 认证时需要先注入 AuthenticationManager,代码如下:
// cn.keeploving.demo.config.SecurityConfig
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception {
return configuration.getAuthenticationManager();
}
然后使用 AuthenticationManager 的 authenticate 方法进行认证是会抛出异常,如下:
- BadCredentialsException:当登录凭证(如密码)错误时抛出的异常
- UsernameNotFoundException:未找到账号时抛出异常
- DisabledException:账号被禁用时抛出的异常
- LockedException:账号被锁定时抛出的异常
还有更多可能排除的异常,但是这几个异常是和账号信息有关的,它们都是 AccountStatusException 的子类,所以登录时可以捕获它们来返回登录失败信息,具体的代码如下:
// cn.keeploving.demo.controller.AuthController
@RestController
@RequestMapping("auth")
public class AuthController {
@Autowired
private AuthenticationManager authenticationManager;
@PostMapping("/login")
public String login(@RequestBody LoginDto loginDto) {
// TODO:验证验证码
// 登录认证
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(loginDto.getUsername(), loginDto.getPassword());
try {
Authentication authenticate = authenticationManager.authenticate(token);
SecurityContextHolder.getContext().setAuthentication(authenticate);
// 生成JWT并返回
Date now = new Date()