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

时间:2015-06-28 20:45:54

标签: spring-security userdetailsservice

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

1)实施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; }}

security-config.xml

2)在<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> 中写下该用户的配置,如下所示:

loadUserByUsername

但现在我想拥有其他类型的用户(admin)。所以,我需要ROLE_ADMIN方法的另一种实现方式(用户将获得AdminServiceImpl) 我可以写另一个类(security-config.xml)但我的{{1}}看起来怎么样?

1 个答案:

答案 0 :(得分:0)

根据建议,切换到数据库存储。假设您正在使用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.
    }

}