2017-06-16 49 views
0

我正在使用Apache Shiro(v1.2.3),並且我正確設置了用戶名/密碼認證,並且它正在工作(我正在將密碼哈希和salt存儲在遠程數據庫中)。我現在試圖使用角色設置權限。我有一個延伸AuthorizingRealm的單一領域,例如Apache Shiro角色和權限不起作用

public class MyRealm extends AuthorizingRealm { 

    @Override 
    protected AuthenticationInfo doGetAuthenticationInfo(
      AuthenticationToken token) throws AuthenticationException { 
     // no problems here... 
    } 

    @Override 
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principles) { 
     Set<String> roles = // get the roles for this user from the DB 
     LOG.info("Found roles => " + roles.toString()); 
     return new SimpleAuthorizationInfo(roles); 
    } 

} 

shiro.ini看起來像這樣:

[主要]
MYREALM = ie.enki.closing.users.MyRealm

credentialsMatcher = org.apache.shiro.authc。憑證.Sha256CredentialsMatcher
credentialsMatcher.storedCredentialsHexEncoded = false
credentialsMatcher.hashIterations = 1024

myRealm.credentialsMatcher = $ credentialsMatcher

的CacheManager = org.ehcache.integrations.shiro.EhcacheShiroManager
securityManager.cacheManager = $ CacheManager的

[角色]
管理員= *
人員= resource_1:action_1

ehcache bein的相關啓動日誌記錄報告克設置正確,但它確實之前,它也提到了這一點:

[主要] INFO org.apache.shiro.realm.text.IniRealm - IniRealm限定,但 沒有定義[用戶]部分。這個領域不會是 與任何用戶填充,並且假定他們將以編程方式填充 。用戶必須爲此Realm實例定義爲 有用。
[main] INFO org.apache.shiro.realm.AuthorizingRealm - 沒有緩存 或cacheManager屬性已設置。授權緩存不能獲得 。
...
一些的Ehcache安裝程序日誌記錄...

在我的測試,currentUser.isPermitted("resource_1:action_1")返回false即使我的記錄說,我確實有admin作用(我與staff角色試過太)。

四郎文檔談論像shiro.ini角色設置一個[用戶]部分和分配給用戶:

[用戶]
some_user =密碼,基於role1,role2所

...但我不想在ini文件中定義用戶及其密碼。這就是我的數據庫的用途。我誤解了配置中的某些內容嗎?

再次瀏覽文檔後,[角色]部分似乎只適用於使用[users]部分定義少量靜態用戶的情況。如果這是真的,你如何將角色與數據庫中定義的用戶的權限相關聯。 docs that might reveal this info不完整。

回答

1

當您不使用IniRealm時,您不直接映射角色 - >權限。您必須告訴Shiro用戶使用SimpleAuthorizationInfoaddStringPermissionsaddObjectPermissions的權限以及您是否使用角色分配權限組來手動檢索這些權限。

根據您的應用程序,有多種方法可以做到這一點。不知道你的應用程序有多複雜,很難推薦一種方法。爲了獲得最大的靈活性,您可以創建3個數據庫表:USER_PERMISSIONS,ROLE_PERMISSIONSUSER_ROLES

如果您只是進行權限檢查,我建議doGetAuthorizationInfo只檢索分配給用戶的權限。角色只能在前端使用,以幫助爲特定用戶分配權限組。這是Shiro在Roles推薦的明確角色。

@Override 
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principles) { 
    Set<String> permissions = // get the permissions for this user from the DB 
    SimpleAuthorizationInfo simpleAuth = new SimpleAuthorizationInfo(); 
    simpleAuth.addStringPermissions(permissions); 
    return simpleAuth; 
} 

P.S.我將刪除[roles]部分,並明確定義您的領域爲Shiro。不建議使用Implicit Assignment。爲此,請在刪除[roles]後將以下行添加到您的配置中。

securityManager.realms = $myRealm