16

我有一个简单的网络项目。我想在这个项目中访问多个角色是一个 URL。

网址的 sihor.ini 部分

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

当用户管理员的角色访问来宾目录时,我收到 401 错误。

为什么?

shiro 版本 1.2.1

4

2 回答 2

19

还有另一种选择:使用OR提供的角色集而不是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;
    }
}

中的用法shiro.ini是这样的:

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

[urls]
...
/path/to/some/url = anyofroles["role1,role2"]
于 2013-06-24T10:29:05.083 回答
-1

代替

/guest/** = user, roles[admin,guest]

试用

/guest/** = user, roles[admin],roles[guest]
于 2014-09-08T09:27:35.740 回答