0

我从上一个Get authenticated user entity Spring MVC中创建了这个主题,我在其中询问了有关正确获取经过身份验证的用户实体的问题。如果我的 UserDetailsS​​ervice 配置正确,我建议 Principal 对象(例如,在我的视图<sec:authentication property="principal.customFieldName" />中)可以访问我的自定义字段。我的 UserDetailsS​​ervice 是否配置正确以完成此功能?

@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;
    }
}
4

1 回答 1

1

我认为您需要一些额外的步骤才能成功使用

<sec:authentication property="principal.customFieldName" />

在某些页面上:

  1. 添加实现org.springframework.security.core.userdetails.UserDetails接口的自定义用户对象。最简单的方法是扩展现有org.springframework.security.core.userdetails.User类:class CutomUser extends User
  2. 将您的customFieldName属性添加到CutomUser类中。
  3. 在您的方法CutomUser中用作返回类型UserDetailsServiceImpl.loadUserByUsername(...)。此时不要忘记填写customFieldName
于 2013-03-06T09:44:00.093 回答