Apache Shiro角色和权限无效

时间:2017-06-16 15:06:58

标签: java shiro

我正在使用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.MyRealm

     

credentialsMatcher =   org.apache.shiro.authc.credential.Sha256CredentialsMatcher
  credentialsMatcher.storedCredentialsHexEncoded = false
  credentialsMatcher.hashIterations = 1024

     

myRealm.credentialsMatcher = $ credentialsMatcher

     

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

     

[角色]
  admin = *
  staff = resource_1:action_1

相关的启动日志记录报告ehcache正在正确设置但在此之前,它还提到了这一点:

  

[main] INFO org.apache.shiro.realm.text.IniRealm - IniRealm定义,   但没有定义[users]部分。这个领域不会   填充了任何用户,并假设它们将被填充   编程。必须为此Realm实例定义用户   有用。
  [主要] INFO org.apache.shiro.realm.AuthorizingRealm - 没有缓存   或已设置cacheManager属性。授权缓存不能   获得。
  ...
  一些ehcache设置日志...

在我的测试中,currentUser.isPermitted("resource_1:action_1")会返回false,即使我的日志记录显示我确实拥有admin角色(我也尝试过staff角色)

shiro文档谈论在shiro.ini中设置[users]部分并为用户分配角色,如:

  

[用户]
  some_user =密码,role1,role2

...但我不想在ini文件中定义用户及其密码。这就是我的数据库。我是否误解了配置中的某些内容?

再次浏览文档后,似乎[roles]部分仅适用于您使用[users]部分定义少量静态用户的情况。如果是这样,那么如何将角色与数据库中定义的用户的权限相关联。 docs that might reveal this info不完整。

1 个答案:

答案 0 :(得分:2)

如果您未使用IniRealm,则不要直接映射角色 - &gt;权限。您必须告诉Shiro用户对SimpleAuthorizationInfo addStringPermissionsaddObjectPermissions的权限,如果您使用角色分配权限组,请手动检索这些权限。

根据您的应用,有多种方法可以执行此操作。如果不知道您的应用程序有多复杂,那么推荐一种方法就很困难。为了获得最大的灵活性,您可以创建3个数据库表:USER_PERMISSIONSROLE_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
相关问题