我在我的应用程序中使用 Spring Security。我需要在我的应用程序的控制器中登录用户详细信息。
为此,我正在使用这段代码
User loggedInUser = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
但是在运行这段代码时我得到了一个 classcastException
java.lang.ClassCastException: org.springframework.security.core.userdetails.User cannot be cast to model.User
为了解决这个问题,我参考了这个article http://www.theserverside.com/tip/-Spring-Security-Customizing-Your-User-and-Authorization-in
最初我使用了 CustomUserServiceDetails 类
@Service("myUserDetailService")
@Transactional
public class CustomUserDetailsService implements UserDetailsService {
private static final Logger logger = Logger.getLogger(CustomUserDetailsService.class);
@Autowired
private UserDAO userDAO;
public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException, DataAccessException {
// returns the get(0) of the user list obtained from the db
User domainUser = userDAO.getUser(name);
logger.debug("User fetched from database in loadUserByUsername method " + domainUser);
Set<Role> roles = domainUser.getRole();
logger.debug("role of the user" + roles);
Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
for(Role role: roles){
authorities.add(new SimpleGrantedAuthority(role.getRole()));
logger.debug("role" + role + " role.getRole()" + (role.getRole()));
}
boolean credentialNonExpired = true;
return new org.springframework.security.core.userdetails.User(domainUser.getProfileName(), domainUser.getPassword(), domainUser.isAccountEnabled(),
domainUser.isAccountNonExpired(), credentialNonExpired, domainUser.isAccountNonLocked(),authorities);
}
}
但在参考这篇文章后,我从这里删除了 GrantedAuthorities 的设置并将其移至我的 User 类中。在我的 User 类中实现了 spring-security UserDetails 类
现在我的 User 类中有一个额外的属性
@Entity
@Table(name = "user")
public class User implements UserDetails {
private Collection<GrantedAuthority> authorities;
使用 set 方法
public void setAuthorities(Set<Role> roles) {
Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
for(Role role: roles){
authorities.add(new SimpleGrantedAuthority(role.getRole()));}
}
答:我不确定如何将此属性映射到数据库。现有的 User 表架构不包含 GrantedAuthority 列,而且它甚至不是原始类型。我正在使用 Hibernate 进行对象映射。谁能建议我在控制器中获取用户类别信息的正确方法?
B.我还考虑了扩展spring的User类并重载我的User类的构造函数的方法。但是每次我在代码中的任何地方初始化用户时,我都必须提供所有构造函数参数,这根本不好。