Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/hibernate/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
什么';在JavaSpring中获取登录用户的其他属性的最佳方法是什么?_Spring_Hibernate_Hql - Fatal编程技术网

什么';在JavaSpring中获取登录用户的其他属性的最佳方法是什么?

什么';在JavaSpring中获取登录用户的其他属性的最佳方法是什么?,spring,hibernate,hql,Spring,Hibernate,Hql,因此,通过使用下面的行,我们可以提取用户名和密码: SecurityContextHolder.getContext().getAuthentication().getPrincipal(); 但是我想获取登录用户的userId,这是我的自定义用户类的一个属性。所以我决定这样做: CustomUserDetails details = new CustomUserDetails(); ... details.setUser(current);

因此,通过使用下面的行,我们可以提取用户名和密码:

SecurityContextHolder.getContext().getAuthentication().getPrincipal();
但是我想获取登录用户的userId,这是我的自定义用户类的一个属性。所以我决定这样做:

        CustomUserDetails details = new CustomUserDetails(); 
        ...
        details.setUser(current);
        UserDetails myUserDetails = (CustomUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        BeanUtils.copyProperties(details, myUserDetails);
        CustomUserDetails myDetails = details.downCast(myUserDetails);
        Integer userId = myDetails.getUser().getId(); //Fetch the custom property in User class
        user.setId(userId);
然而,我只是通过HQL获取用户,并将其放入一个临时用户类中,这是毫无意义的


那么,获取属性userId的最佳方法是什么?似乎我最好只使用HQL查询(使用登录用户的用户名通过HQL获取用户)。

我将扩展Spring Security
UserDetails
类,并添加应用程序需要的任何适当属性。我们通常专门针对包含
userId
的不可变信息执行此操作

然后,当您需要适当的属性时:

// Get the principal from spring security
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Object principal = authentication.getPrincipal();

// verify principal if your custom user details type.
// if so, get the userid and do whatever.
if(principal != null && principal instanceof CustomUserDetails) {
  CustomUserDetails userDetails = CustomUserDetails.class.cast(principal);
  Long userId = userDetails.getUserId();
  /* do whatever you want with user id */
}

然后在身份验证过程中,当您的
UserDetailsService
实现返回
UserDetails

时,只需创建您自己的
CustomUserDetails
对象,我的应用程序使用类公共类UserDetailsServiceImpl,该类实现UserDetailsService并具有返回UserDetails的方法。在方法中添加用户后,我可以返回customUserDetails,对吗?但我不确定是否可以返回userDetails以外的内容。@jarvan您完全可以创建扩展类
CustomUserDetails
的一个实例,并从该函数返回它的超类类型
userDetails
。我可以原样返回它还是必须强制转换它?@jarvan原样返回它,只需重写该方法。哦,哇,它很有效。您可以返回UserDetails的子类,该子类包含任意数量的类+用户类。