如何在Spring Security上从CustomUser获取用户ID
2022-09-03 00:38:44
usign Spring Security,我正在尝试从我的CustomUser实例中获取用户ID,该实例从我的CustomUserDetailsService上的loadUserByUsername方法返回,就像我获取Name(get.名称()) 与身份验证。感谢您的任何提示!
这是我获取已登录用户的当前名称的方式:
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String name = authentication.getName();
这是自定义用户
public class CustomUser extends User {
private final int userID;
public CustomUser(String username, String password, boolean enabled, boolean accountNonExpired,
boolean credentialsNonExpired,
boolean accountNonLocked,
Collection<? extends GrantedAuthority> authorities, int userID) {
super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
this.userID = userID;
}
}
以及我的服务上的 loadUserByUsername 方法
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
Usuario u = usuarioDAO.getUsuario(s);
return new CustomUser(u.getLogin(), u.getSenha(), u.isAtivo(), u.isContaNaoExpirada(), u.isContaNaoExpirada(),
u.isCredencialNaoExpirada(), getAuthorities(u.getRegraByRegraId().getId()),u.getId()
);
}