2015-06-28 47 views
1

在我的web應用程序時,我有一種類型的用戶(typical_user)我做了以下內容:如何爲幾種類型的用戶實現UserDetailsS​​ervice?

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> 

但現在我想擁有另一種類型的用戶(管理員)。所以,我需要另一個執行loadUserByUsername方法(其中用戶將得到ROLE_ADMIN)。
我可以寫另一個班級(AdminServiceImpl),但我的security-config.xml將如何看起來像?

+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. 
    } 

} 
相關問題