[英]Apache Shiro roles and permissions not working
我正在使用Apache Shiro(v1.2.3),並且正確設置了用戶名/密碼身份驗證,並且可以正常工作(我將密碼哈希和鹽存儲在遠程數據庫中)。 我現在正在嘗試使用角色設置權限。 我有一個擴展AuthorizingRealm
領域
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.MyRealmcertificateMatcher = org.apache.shiro.authc.credential.Sha256CredentialsMatcher
certificateMatcher.storedCredentialsHexEncoded = false
certificateMatcher.hashIterations = 1024myRealm.credentialsMatcher = $ credentialsMatcher
cacheManager = org.ehcache.integrations.shiro.EhcacheShiroManager
securityManager.cacheManager = $ cacheManager[角色]
管理員= *
人員=資源_1:操作_1
相關的啟動日志記錄報告ehcache已正確設置,但在此之前,它也提到了這一點:
[main] INFO org.apache.shiro.realm.text.IniRealm-已定義IniRealm,但未定義[users]部分。 此領域不會填充任何用戶,並且假定將以編程方式填充他們。 必須定義用戶,此Realm實例才有用。
[main] INFO org.apache.shiro.realm.AuthorizingRealm-尚未設置cache或cacheManager屬性。 無法獲得授權緩存。
...
一些ehcache設置日志記錄...
在我的測試中,即使我的日志顯示我確實具有admin
角色(我也嘗試過使用staff
角色), currentUser.isPermitted("resource_1:action_1")
返回false
。
shiro docs討論了在shiro.ini
設置[users]部分並為用戶分配角色,例如:
[使用者]
some_user =密碼,角色1,角色2
...但是我不想在ini文件中定義用戶及其密碼。 那就是我的數據庫的用途。 我是否誤解了配置中的某些內容?
再次瀏覽文檔后,似乎[roles]部分僅在您使用[users]部分定義少量靜態用戶時才適用。 如果是這樣,您如何將角色與數據庫中定義的用戶的權限相關聯。 可能顯示此信息的文檔不完整。
當您不使用IniRealm
,您不會直接映射IniRealm
> Permissions。 您必須告訴Shiro用戶對SimpleAuthorizationInfo
的addStringPermissions或addObjectPermissions擁有哪些權限,並且是否要使用角色來分配權限組以手動檢索這些權限。
有多種方法可以執行此操作,具體取決於您的應用程序。 在不知道您的應用程序有多復雜的情況下,很難推薦一種方法。 為了獲得最大的靈活性,您可以創建3個數據庫表: USER_PERMISSIONS
, ROLE_PERMISSIONS
和USER_ROLES
。
如果您僅在進行權限檢查,則建議doGetAuthorizationInfo
僅檢索分配給用戶的權限。 角色將僅在前端使用,以協助將權限組分配給某些用戶。 這是Shiro在“ 角色”中建議的“顯式角色” 。
@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;
}
PS我將刪除[roles]
部分,並明確定義Shiro的領域。 不建議隱式分配 。 為此,請在刪除[roles]
之后將以下行添加到您的配置中。
securityManager.realms = $myRealm
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.