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

时间:2014-03-27 05:19:32

标签: java spring authentication spring-security

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

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

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

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

我的服务上的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()
    );
}

2 个答案:

答案 0 :(得分:17)

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

如果您还没有,请添加getUserId() getter方法。

答案 1 :(得分:0)

您可以在控制器中获取 userId,如下所示。从此 example 获取更多信息。请记住,您在创建 JWT 时已将所需的身份验证信息设置到其中以便使用它们。

@Controller
public class GetUserWithHTTPServletRequestController {

    @RequestMapping(value = "/username", method = RequestMethod.GET)
    @ResponseBody
    public String currentUserNameSimple(HttpServletRequest request) {
        Principal principal = request.getUserPrincipal();
        return principal.getName();
    }
}

或如下,

@PostMapping(value = "/sample")
public String sample(@RequestBody SampleDto sampleDto, Principal principal) {
    String username = principal.getName();
    // You can get other Auth details from principal Object
    return "success";
}