java Apache Shiro角色和权限不起作用
我正在使用ApacheShiro(v1.2.3),我已经正确地设置了用户名/密码身份验证,并且它正在工作(我正在远程数据库中存储密码哈希和salt)。我现在正在尝试使用角色设置权限。我有一个扩展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
看起来像这样:
[main]
myRealm = ie.enki.closing.users.MyRealmcredentialsMatcher = org.apache.shiro.authc.credential.Sha256CredentialsMatcher
credentialsMatcher.storedCredentialsHexEncoded = false
credentialsMatcher.hashIterations = 1024myRealm.credentialsMatcher = $credentialsMatcher
cacheManager = org.ehcache.integrations.shiro.EhcacheShiroManager
securityManager.cacheManager = $cacheManager[roles]
admin = *
staff = resource_1:action_1
相关的启动日志报告ehcache正在正确设置,但在此之前,它还提到:
[main] INFO org.apache.shiro.realm.text.IniRealm - IniRealm defined, but there is no [users] section defined. This realm will not be populated with any users and it is assumed that they will be populated programatically. Users must be defined for this Realm instance to be useful.
[main] INFO org.apache.shiro.realm.AuthorizingRealm - No cache or cacheManager properties have been set. Authorization cache cannot be obtained.
...
some ehcache setup logging...
在我的测试中,currentUser.isPermitted("resource_1:action_1")
返回false
,尽管我的日志显示我确实拥有admin
角色(我也尝试过使用staff
角色)
shiro文档讨论了在shiro.ini
中设置[users]部分,并为用户分配角色,如:
[users]
some_user = password, role1, role2
。。。但我不想在ini文件中定义用户及其密码。这就是我的数据库的用途。我是否误解了配置中的某些内容
在再次浏览文档之后,[roles]部分似乎只适用于使用[users]部分定义少量静态用户的情况。如果是这样,那么如何将角色与数据库中定义的用户权限相关联。{a1}是不完整的
# 1 楼答案
当您不使用
IniRealm
时,您不会直接映射角色->;权限。你必须告诉Shiro用户对SimpleAuthorizationInfo
的addStringPermissions或addObjectPermissions有什么权限,如果你使用角色分配权限组,手动检索这些权限根据你的应用,有多种方法可以做到这一点。在不知道应用程序有多复杂的情况下,很难推荐一种方法。为了获得最大的灵活性,可以创建3个数据库表:
USER_PERMISSIONS
、ROLE_PERMISSIONS
和USER_ROLES
如果你只做权限检查,我建议
doGetAuthorizationInfo
只检索分配给用户的权限。角色仅在前端用于协助将权限组分配给特定用户。这是Shiro在Roles中推荐的明确角色另外,我会删除
[roles]
部分,并明确地将您的领域定义为Shiro^不建议使用{a4}。要做到这一点,请在删除[roles]
后将以下行添加到配置中