shiro框架总共有四种权限控制方式:
1, URL拦截权限控制
2,方法注解权限控制
3,页面标签权限控制
4,代码级别权限控制(了解)
1,URL拦截权限控制:
<!--注入URL拦截规则 -->
<property name="filterChainDefinitions">
<value>
/css/** = anon
/js/** = anon
/easyUI/** = anon
/images/** = anon
/validatecode.jsp* = anon
/login.jsp = anon
/userAction_login = anon
/page_base_staff.action = perms["staff-list"]
/* = authc
</value>
</property>
2,方法注解的拦截:
第一步:在spring配置文件中开启shiro注解支持
<!-- 开启shiro框架注解支持 -->
<bean id="defaultAdvisorAutoProxyCreator"
class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator">
<!-- 必须使用cglib方式为Action对象创建代理对象 -->
<property name="proxyTargetClass" value="true"/>
</bean>
<!-- 配置shiro框架提供的切面类,用于创建代理对象 -->
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor"/>
第二步:在Action的方法上使用shiro注解
// 批量删除@RequiresPermissions("starff-delete")
public String deleteBatch(){
ss.deleteByIds(ids);
return "list";
}
第三步:在struts.xml中配置全局异常捕获,当shiro框架抛出权限不足异常时,跳转到权限不足提示页面
<!-- 全局结果集的定义 -->
<global-results>
<result name="login" type="redirect">/login.jsp</result>
<result name="unauthorizedException" type="redirect">/validatecode.jsp</result>
</global-results>
<global-exception-mappings>
<exception-mapping result="unauthorizedException" exception="org.apache.shiro.authz.UnauthorizedException"></exception-mapping>
</global-exception-mappings>
3, 在realm中进行授权
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection pricipals) {
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
// 获得当前用户对象
User user = (User) SecurityUtils.getSubject().getPrincipal();
// User user2 = (User) pricipals.getPrimaryPrincipal();
// 根据用户对象查询数据库,获得相应的权限
List<Function> list = null;
if(user.getUsername().equals("zhangsan")){
//如果用户名是admin/zhangsan,授予所有权限
list = fd.findAll();
// 为用户授权
info.addStringPermission("staff-list");
}else{
// 普通用户,根据用户的id去查询权限
list = fd.findAllFunctionById(user.getId());
}
for (Function function : list) {
info.addStringPermission(function.getCode());
}
return info;
}
4,使用shiro提供的页面标签方法进行权限控制
<shiro:hasPermission name="staff-delete">
{
id : 'button-delete',
text : '删除',
iconCls : 'icon-cancel',
handler : doDelete
},
</shiro:hasPermission>
5,代码级别的权限控制