UserDetailsS​​ervice配置用于正确获取用户

时间:2013-03-06 07:15:01

标签: spring spring-security

我从之前的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;
    }
}

1 个答案:

答案 0 :(得分: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