Search code examples
javaapacherestpermissionsshiro

Apache shiro + HTTP method level permission


I am developing a REST based web application where rest services has Apache shiro integrated to perform basic authentication and role based authorization.

Now I want to enhance the authorization functionality with permissions configuration at method level(Micro service in case of REST). If I am not wrong, Apache shiro provides HttpMethodPermissionFilter class which can be used as filter to restrict incoming requests based on its HTTP method(GET,POST,DELETE,HEAD etc...) which internally checks for the permissions from the roles_permissions table of database we configured or INI configuration file.

So to implement HTTP method based permission functionality, Do I need to make any changes in my shiro.ini file. Or my jdbc realm has something to do.

shiro.ini file

[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

custom jdbc realm

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;
    }
}

I am new to apache shiro so any reference would be grateful. Thanks.


Solution

  • Take a look at the doc for the HttpMethodPermissionFilter, lets say you have the following CRUD permissions for /rest/page1 :

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

    Your [urls] mapping would look like this:

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

    All GET requests to /rest/page1/** would be mapped to the permission rest[abc:read]