usign Spring Security,我正在尝试从我的 CustomUserDetailsService 上的 loadUserByUsername 方法返回的 CustomUser 实例中获取用户 ID,就像我通过身份验证获取名称 (get.Name()) 一样。感谢您提供任何提示!
这是我获取登录用户的当前名称的方式:
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()
);
}
最佳答案
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/