2011-04-11 82 views

回答

1

對於我所引用的帖子,接受的答案似乎並不正確。您不必爲此創建自己的UserDetailsService實現。已經支持多個角色。見JdbcDaoImpl。您必須確保authoritiesByUsernameQuery與您的數據庫設置相匹配。默認情況下,它的值是select username,authority from authorities where username = ?。該查詢由加載所有權限的loadUserAuthorities方法執行。

+0

我嘗試這樣做,而不是分裂ROLE_ADMIN,ROLE_USER分成2個角色,我把整個字符串看作是一個單獨的角色「ROLE_ADMIN,ROLE_USER」,這不用說不起作用 – markbaldy 2013-06-05 06:56:11

+0

@markbaldy我不知道我是否得到了這個問題。你可以添加代碼來顯示你已經嘗試過嗎? – Ritesh 2013-06-06 06:47:20

+0

使用您的解決方案,整個字符串作爲單個權限返回:「ROLE_ADMIN,ROLE_USER」,而不是[「ROLE_ADMIN」,「ROLE_USER」]。我確實需要實現我自己的UserDetailsS​​ervice。 – markbaldy 2013-06-07 07:04:05

0

如果有人有興趣的逗號分隔當局自定義的UserDetailsS​​ervice:

@Component 
public class MyUserDetailsService implements UserDetailsService { 

    @Resource 
    private AccountService accounts; 

    @Override 
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 

     Account account = accounts.findByUsername(username); 
     if(null == account) { 
      throw new UsernameNotFoundException("User " + username + " not found."); 
     } 

     List<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>(); 
     String[] authStrings = account.getAuthorities().split(", "); 
     for(String authString : authStrings) { 
      authorities.add(new SimpleGrantedAuthority(authString)); 
     } 

     UserDetails ud = new User(account.getUsername(), account.getPassword(), authorities); 
     return ud; 
    } 

} 

現在你可以在DB是這樣的:

+----+-----------------------+----------+----------+ 
| id | authorities   | password | username | 
+----+-----------------------+----------+----------+ 
| 1 | ROLE_ADMIN   | 123qwe | markm | 
| 2 | ROLE_ADMIN, ROLE_USER | 123qwe | kemika | 
+----+-----------------------+----------+----------+ 
+0

如何配置spring配置文件以支持將多個角色分配給單個用戶? – seph 2016-02-26 14:45:57