java - 如何从 Spring Security 的 CustomUser 获取用户 ID

标签 java spring authentication spring-security

usign Spring Security,我正在尝试从我的 CustomUserDetailsS​​ervice 上的 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/

相关文章:

java - 如何在java中的任何特定节点之前添加xml中的节点

java - 我应该应用多少测试来测试双向链表?

java - Charset.defaultCharset() 和 file.encoding 有什么区别?

authentication - Paw - 支持 https 相互(客户端证书)身份验证?

authentication - 使用 openSSL 验证我的自签名证书

java - 如何知道是Applet还是Application

java - Spring JDBC : Returning 0 or 1 rows

spring - JavaFx 12 Spring,Maven 未找到前缀插件

java - BeanFactory未初始化或已关闭spring security

javascript - 使用 Ember-Auth 成功登录后如何转换为 root?