Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

apache shiro allowing multiple roles to Access a url not working

Tags:

shiro

I have a simple web project. I want to have access to more than one role in this project is a URL.

sihor.ini section of the url

[urls]
/login.xhtml = authc
/logout = logout
/admin/** = user, roles[admin]
/guest/** = user, roles[admin,guest]

I'm getting a 401 error when the role of a user admin visit to guest directory.

Why?

shiro version 1.2.1

like image 257
Rhododendron Avatar asked Feb 20 '13 13:02

Rhododendron


People also ask

How does Apache Shiro work?

Apache Shiro's design goals are to simplify application security by being intuitive and easy to use. Shiro's core design models how most people think about application security - in the context of someone (or something) interacting with an application. Software applications are usually designed based on user stories.

What is Shiro ini?

The [users] section of the shiro. ini config file defines the user credentials that are recognized by the SecurityManager. The format is: principal (username) = password, role1, role2, …, role. The roles and their associated permissions are declared in the [roles] section.


1 Answers

There's another option: custom implementation of roles filter using OR for the provided role set instead of AND.

import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.RolesAuthorizationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

/**
 * Allows access if current user has at least one role of the specified list.
 * 
 * Basically, it's the same as {@link RolesAuthorizationFilter} but using {@literal OR} instead
 * of {@literal AND} on the specified roles.
 *
 * @see RolesAuthorizationFilter
 * @author Andy Belsky
 */
public class AnyOfRolesAuthorizationFilter extends RolesAuthorizationFilter {

    @Override
    public boolean isAccessAllowed(ServletRequest request, ServletResponse response,
                                   Object mappedValue) throws IOException {

        final Subject subject = getSubject(request, response);
        final String[] rolesArray = (String[]) mappedValue;

        if (rolesArray == null || rolesArray.length == 0) {
            //no roles specified, so nothing to check - allow access.
            return true;
        }

        for (String roleName : rolesArray) {
            if (subject.hasRole(roleName)) {
                return true;
            }
        }

        return false;
    }
}

The usage in shiro.ini is like this:

[main]
...
anyofroles = com.your.package.AnyOfRolesAuthorizationFilter

[urls]
...
/path/to/some/url = anyofroles["role1,role2"]
like image 60
Andy Avatar answered Sep 16 '22 22:09

Andy