Apache shiro + HTTP方法级别权限

时间:2017-01-29 08:18:13

标签: java apache rest permissions shiro

我正在开发一个基于REST的Web应用程序,其中休息服务集成了Apache shiro,以执行基本身份验证和基于角色的授权。

现在,我想通过方法级别的权限配置来增强授权功能(如果是REST,则为微服务)。如果我没有错,Apache shiro提供了HttpMethodPermissionFilter类,它可以用作过滤器来根据其HTTP方法(GET,POST,DELETE,HEAD等...)来限制传入请求,这些方法在内部检查来自roles_permissions表的权限。我们配置的数据库或INI配置文件。

因此,要实现基于HTTP方法的权限功能,我是否需要在shiro.ini文件中进行任何更改。或者我的jdbc领域有事可做。

shiro.ini文件

[main]
userRoles = org.apache.shiro.web.filter.authz.RolesAuthorizationFilter

jdbcRealm = my.custom.jdbc.realm.YhJdbcRealm
securityManager.realms = $jdbcRealm

[urls]
# Allowing login page to any user
/rest/login/** = anon

# Page 1
/rest/page1/** = noSessionCreation, authcBasic, userRoles[role1]


# page 2
/rest/page2/** = noSessionCreation, authcBasic, userRoles[role1,role2,role3]


# page 3
/yhrest/page3/** = noSessionCreation, authcBasic, userRoles[role1,role3]

/rest/** = noSessionCreation, authcBasic

自定义jdbc领域

public class YhJdbcRealm extends JdbcRealm
{
    public YhJdbcRealm()
    {
        loadDataSource();
    }

    private void loadDataSource()
    {
        this.dataSource = JdbcConnection.initConnection();
        this.permissionsLookupEnabled = true;
        this.authenticationQuery = "SELECT password FROM users WHERE username = ?";
        this.userRolesQuery = "SELECT role_name FROM user_roles WHERE username = ?";
        this.permissionsQuery = "SELECT permission FROM roles_permissions_temp WHERE role_name = ?";
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException
    {
        AuthenticationInfo info = super.doGetAuthenticationInfo(token);
        return info;
    }
}

我是apache shiro的新手,所以任何参考都会感激不尽。 感谢。

1 个答案:

答案 0 :(得分:0)

查看HttpMethodPermissionFilter的文档,假设您对/rest/page1拥有以下CRUD权限:

  • abc:create
  • abc:read
  • abc:update
  • abc:delete

您的[urls]映射看起来像这样:

[urls]
/rest/page1/** = noSessionCreation, authcBasic, rest[abc]

/rest/page1/**的所有GET请求都会映射到权限rest[abc:read]