我从之前的Get authenticated user entity Spring MVC创建了此主题,在那里我询问了有关正确获取经过身份验证的用户实体的问题。我建议,如果我的UserDetailsService配置正确,Principal对象(例如,在我的视图<sec:authentication property="principal.customFieldName" />
上)可以访问我的自定义字段。我的UserDetailsService是否已正确配置以完成此功能?
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
private static final Logger logger = Logger.getLogger(UserDetailsServiceImpl.class);
@Autowired
@Qualifier("hibernateUserDao")
private UserDAO userDAO;
@Override
@Transactional(readOnly = true)
public org.springframework.security.core.userdetails.UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException, DataAccessException {
UserDetails user = userDAO.findByLogin(userName);
if (user == null) {
logger.error("User was not found! Input login: " + userName);
}
return buildUserFormUserEntity(user);
}
@Transactional(readOnly = true)
private org.springframework.security.core.userdetails.User buildUserFormUserEntity(UserDetails userDetails) {
boolean enableStatus = userDetails.isEnabled();
String userName = userDetails.getLogin();
String password = userDetails.getPassword();
boolean enabled = enableStatus;
boolean accountNonExpired = enableStatus;
boolean credentialsNonExpired = enableStatus;
boolean accountNonLocked = enableStatus;
Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
authorities.add(new SimpleGrantedAuthority(userDetails.getRole()));
User springSecurityUser = new User(userName, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
return springSecurityUser;
}
public UserDAO getUserDAO() {
return userDAO;
}
public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
}
}
答案 0 :(得分:1)
我认为您需要一些额外的步骤才能成功使用
<sec:authentication property="principal.customFieldName" />
某页上的:
org.springframework.security.core.userdetails.UserDetails
界面的自定义用户对象。最简单的方法是扩展现有的org.springframework.security.core.userdetails.User
类:class CutomUser extends User
customFieldName
媒体资源添加到CutomUser
课程。CutomUser
方法中使用UserDetailsServiceImpl.loadUserByUsername(...)
作为返回类型。此时不要忘记填写customFieldName
。