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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22678891/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 17:14:38  来源:igfitidea点击:

How to get User ID from CustomUser on Spring Security

javaspringauthenticationspring-security

提问by Joao Evangelista

usign Spring Security ,I'm trying to get the user id from my CustomUser instance returned from loadUserByUsername method on my CustomUserDetailsService, like I do to get get the Name (get.Name()) with Authentication. Thanks for any tips!

使用 Spring Security,我试图从我的 CustomUserDetailsS​​ervice 上的 loadUserByUsername 方法返回的 CustomUser 实例中获取用户 ID,就像我通过身份验证获取名称 (get.Name()) 一样。感谢您提供任何提示!

This is how I get the current name of logged user:

这是我获取登录用户的当前名称的方式:

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String name = authentication.getName();

And this is the CustomUser

这是 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;
    }
}

And the loadUserByUsername method on my Service

以及我的 Service 上的 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()
    );
}

采纳答案by holmis83

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

You have to add the getUserId()getter method if you don't already have it.

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