使用Spring Security,我正在尝试从CustomUserDetailsService上的loadUserByUsername方法返回的CustomUser实例中获取用户ID,就像我通过身份验证获取名称(get.Name())一样。感谢您的提示!
这是我如何获取登录用户的当前名称:
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String name = authentication.getName();
这是CustomUser
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()
);
}
最佳答案
Authentication authentication = ...
CustomUser customUser = (CustomUser)authentication.getPrincipal();
int userId = customUser.getUserId();
如果还没有
getUserId()
getter方法,则必须添加它。关于java - 如何在Spring Security上从CustomUser获取用户ID,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22678891/