2014年6月4日 星期三

[Shiro] url get multiple roles

在spring-security中,如果要對網址控管多個角色可進入
一般會透過roles[admin]
ex: /admin/** = user, roles[admin] 

但是 roles["admin,guest"] ,會被認定要符合這些角色(hasAllRoles)
因此,必須自己去定義,改寫RolesAuthorizationFilter就可以
參考這篇
http://blog.abelsky.com/2014/01/27/make-apache-shiro-allow-several-roles-to-access-resource/

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

最後在spring-security.xml中加入
<bean id="anyOfRoles" class="com.your.package.AnyOfRolesAuthorizationFilter" />
就可以透過anyOfRoles去使用多個角色
/path/to/some/url = anyofroles["role1,role2"]

Other reference:
http://shiro-user.582556.n2.nabble.com/Shiro-ini-multiple-roles-for-one-url-td6806837.html

沒有留言:

張貼留言