我已经使用REST API约定构建了Java应用程序。我在端点上工作,仅当对象通过数据库中的公共ID与用户连接时才返回对象(ManyToOne批注)。为了实现这一点,我需要当前登录的用户ID才能将其与对象的用户ID进行映射。如果ID相同,则端点返回数据。我知道解决方案是“ Principal”或“ Authentication”类,但它们提供了除“ id”之外的所有内容。我使用spring security http basic进行身份验证。
有人知道如何解决该问题吗?
您可以使用UserDetails
类并为username
字段设置ID,该类由Spring安全性提供。
如果您不需要该解决方案,则可以创建Subclass extend UserDetails
类并确定id字段。收到请求时,将主体解析为UserDetails
或subclass extends UserDetails
以获取ID
Ex:
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
UserDetails userPrincipal = (UserDetails)authentication.getPrincipal();