首先在一个请求访问服务端后,服务端会开辟一个线程对当前请求进行处理
对信息进行一个认证,在server中进行认证
//准备被认证数据
Authentication authentication = new UsernamePasswordAuthenticationToken(
adminLoginDTO.getUsername(), adminLoginDTO.getPassword());
//调用AuthenticationManager验证用户名与密码
//执行认证,如果此过程没有抛出异常,则表示认证通过,如果认证信息有误,将抛出异常
authenticationManager.authenticate(authentication);
在调用authenticationManager.authenticate(authentication);方法要创建一个类UserDetailsServiceImpl,并实现UserDetailsService接口,使其在进行认证时可使用自己数据库的信息去进行一个验证
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private AdminMapper adminMapper;
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
System.out.println("根据用户名查询尝试登录的管理员信息,用户名=" + s);
AdminLoginVO admin = adminMapper.getLoginInfoByUsername(s);
System.out.println("通过持久层进行查询,结果=" + admin);
if (admin == null) {
System.out.println("根据用户名没有查询到有效的管理员数据,将抛出异常");
throw new BadCredentialsException("登录失败,用户名不存在!");
}
System.out.println("查询到匹配的管理员数据,需要将此数据转换为UserDetails并返回");
UserDetails userDetails = User.builder()
.username(admin.getUsername())
.password(admin.getPassword())
.accountExpired(false)
.accountLocked(false)
.disabled(admin.getIsLogin() != 1)
.credentialsExpired(false)
.authorities(admin.getPermissions().toArray(new String[] {}))
.build();
System.out.println("转换得到UserDetails=" + userDetails);
return userDetails;
}
}
并在认证信息成功后在过滤器Filter中将认证信息封装成一个authentication存入安全上下文中
//后续,Spring Security发现上下文中有Authentication时,就会视为已登录,可以获取相关信息
Authentication authentication = new UsernamePasswordAuthenticationToken(username, null, permissions);
SecurityContextHolder.getContext().setAuthentication(authentication);
后续,Spring Security发现上下文中有Authentication时,就会视为已登录,可以获取相关信息