Shiro 自定义角色 认证

时间:2022-02-27 08:23:32

转载,原博文的地址在:https://ailongni.iteye.com/blog/2086022

由于Shiro filterChainDefinitions中 roles默认是and,
/** = user,roles[system,general]
比如:roles[system,general] ,表示同时需要“system”和“general” 2个角色才通过认证
所以需要自定义 继承 AuthorizationFilter

public class RolesAuthorizationFilter extends AuthorizationFilter{

    @Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
throws Exception {
Subject subject = getSubject(request, response);
String[] rolesArray = (String[]) mappedValue; if (rolesArray == null || rolesArray.length == 0) {
//no roles specified, so nothing to check - allow access.
return true;
} for(int i=0;i<rolesArray.length;i++){
if(subject.hasRole(rolesArray[i])){
return true;
}
}
return false;
} }

shiro过滤器xml配置:

<!-- Shiro Filter -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager" />
<property name="loginUrl" value="/login" />
<property name="successUrl" value="/success" />
<property name="filters">
<map>
<entry key="anyRoles" value-ref="anyRoles"/>
</map>
</property>
<property name="filterChainDefinitions">
<value>
/login = authc
/login/logout = anon
/ = anon
/XXX/** = user,anyRoles[system,general]
/TTT = role[system]
/** = user
</value>
</property>
</bean> <!--自定义的Roles Filter-->
<bean id="anyRoles" class="com.jianfei.p.web.common.RolesAuthorizationFilter" />

注意:/XXX/** = user,anyRoles[system,general], 注意红色的"anyRoles"一定要和

<entry key="anyRoles" value-ref="anyRoles"/> key一样就行,否则过滤器不起作用