如何为几种类型的用户实现 UserDetailsS​​ervice?

How implement UserDetailsService for several types of users?

在我的网络应用程序中,当我有一种类型的用户 (typical_user) 时,我会执行以下操作:

1) 实施 UserDetailsService

public class UserServiceImpl implements UserService, UserDetailsService {
private UserDao userDao;
@Override
public UserDetails loadUserByUsername(String username)
        throws UsernameNotFoundException
{
    UserEntity user = userDao.loadUserByEmail(username);

    if (user == null) {
        throw new UsernameNotFoundException(String.format(
                getMessageBundle().getString("badCredentials"), username));
    }

    Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    authorities.add(new SimpleGrantedAuthority("ROLE_USER"));

    User userDetails = new User(user.getEmail(), user.getPassword(),
            authorities);

    return userDetails;
}}

2) 在 security-config.xml 中为该用户编写配置,如下所示:

<security:authentication-manager>
    <security:authentication-provider
        user-service-ref="userService">
        <security:password-encoder hash="md5" />
    </security:authentication-provider>
</security:authentication-manager>

<bean id="daoAuthenticationProvider"
    class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
    <property name="userDetailsService" ref="userService" />
    <property name="hideUserNotFoundExceptions" value="false" />
</bean>

但现在我想要另一种类型的用户(admin)。所以,我需要另一个 loadUserByUsername 方法的实现(用户将在其中获得 ROLE_ADMIN)。
我可以写另一个 class (AdminServiceImpl) 但我的 security-config.xml 会是什么样子??

按照建议,切换到数据库存储。假设您使用 ORM 进行数据库管理:

public class Role implements org.springframework.security.core.GrantedAuthority {
    // implements what must be implemented
}

public class User implements org.springframework.security.core.userdetails.UserDetails {

    // your stuff...

    @ManyToMany(fetch = FetchType.EAGER) // shouldn't be a problem here to fetch eagerly
    private Collection<Role> roles = new HashSet<Role>();

    // add getters and setters

    /**
     * @see org.springframework.security.core.userdetails.UserDetails#getAuthorities()
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return getRoles();
    }

}

public class UserDetailsServiceImpl implements
    org.springframework.security.core.userdetails.UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String username)
        throws UsernameNotFoundException {
        // Load the user from your database. The ORM will take care of loading his Role collection.
    }

}