【问题标题】:How to get User ID from CustomUser on Spring Security如何从 Spring Security 上的 CustomUser 获取用户 ID
【发布时间】:2014-05-05 21:52:32
【问题描述】:

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

【问题讨论】:

    标签: java spring authentication spring-security


    【解决方案1】:
    Authentication authentication = ...
    CustomUser customUser = (CustomUser)authentication.getPrincipal();
    int userId = customUser.getUserId();
    

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

    【讨论】:

    • Principal 可以注入。
    • 通过方法参数注入:@AuthenticationPrincipal CustomUser customUser
    猜你喜欢
    • 2015-06-02
    • 2013-11-29
    • 1970-01-01
    • 2018-01-25
    • 2015-12-06
    • 2012-04-22
    • 2019-07-24
    • 2020-02-12
    • 2021-08-06
    相关资源
    最近更新 更多