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

Joa*_*sta 8 java authentication spring spring-security

使用Spring Security,我试图从我的CustomUserDetailsS​​ervice上的loadUserByUsername方法返回我的CustomUser实例中的用户id,就像我获取带有Authentication的Name(get.Name())一样.谢谢你的任何提示!

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

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String name = authentication.getName();
Run Code Online (Sandbox Code Playgroud)

这是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;
    }
}
Run Code Online (Sandbox Code Playgroud)

和我的服务上的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()
    );
}
Run Code Online (Sandbox Code Playgroud)

hol*_*s83 17

Authentication authentication = ...
CustomUser customUser = (CustomUser)authentication.getPrincipal();
int userId = customUser.getUserId();
Run Code Online (Sandbox Code Playgroud)

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

  • 通过方法参数注入:@AuthenticationPrincipal CustomUser customUser (5认同)
  • `Principal`可以注入. (2认同)