如何在Spring Security上从CustomUser获取用户ID

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()
    );
}

答案 1
Authentication authentication = ...
CustomUser customUser = (CustomUser)authentication.getPrincipal();
int userId = customUser.getUserId();

如果您还没有 getter 方法,则必须添加它。getUserId()


答案 2

推荐