1.在配置文件中
<!-- 此bean要被web.xml引用,和web.shiroFilter -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!-- 权限管理器 -->
<property name="securityManager" ref="securityManager"/>
<!-- 登录地址 -->
<property name="loginUrl" value="/pages/login.jsp"/>
<!-- 登录后跳转到业务页面 -->
<property name="successUrl" value="/pages/home.jsp"/>
<!-- 错误页面 -->
<property name="unauthorizedUrl" value="/pages/unauthorized.jsp"/>
<!-- 权限配置 -->
<property name="filterChainDefinitions">
<value>
<!-- 匿名登录请求 -->
/public/** = anon
<!-- **代表任意子目录 -->
/static/**=anon
<!-- 需要权限为edit的用户才能访问此请求-->
/user/edit=perms[user:edit]
<!-- 需要管理员角色才能访问此页面 -->
<!--/user/edit=roles[admin]-->
<!--拦截非静态资源的所有请求-->
/** = authc
<!--authc:确保已认证的用户发送的请求才能通过(若未认证,则跳转到登录页面)-->
</value>
</property>
</bean>
2.注解上定义
2.1 开启注解
<!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
<!-- 安全管理器 -->
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager"/>
</bean>
<!--启用Shiro相关的注解-->
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
depends-on="lifecycleBeanPostProcessor"/>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager"/>
</bean>
2.2 controller
在UserController方法上面加注解:
@RequestMapping(value = "/list", method = {RequestMethod.GET, RequestMethod.POST})
@RequiresPermissions("user:edit")
public String list(Model model) {
return "/list";
}
2.3 jsp页面:
<shiro:hasPermission name="user:edit">
<p>你有权限看到此处!</p>
</shiro:hasPermission>
由于我们是在springmvc-context.xml中开启controller注解的,所以只在spring-context.xml中导入shiro-context.xml,是无法成功启用注解的,所以最好在spring-context.xml和springmvc-context.xml中均加入:
<import resource="shiro-context.xml"/>
2.4.shiro权限标签
标签 | 功能 |
<shiro:guest>...</shiro:guest> | 判断当前用户是否为游客 |
<shiro:user>...</shiro:user> | 判断当前用户是否已登录(包括:已认证或已记住) |
<shiro:authenticated>...</shiro:authenticated> | 判断当前用户是否已认证通过(不包括已记住 |
<shiro:notAuthenticated>...</shiro:notAuthenticated> | 判断当前用户是否未认证通过 |
<shiro:principal /> | 获取当前用户的相关信息,例如:用户名 |
<shiro:hasRole name="foo">...</shiro:hasRole> | 判断当前用户是否具有某种角色 |
<shiro:lacksRole name="foo">...</shiro:lacksRole> | 判读当前用户是否缺少某种角色 |
<shiro:hasAnyRoles name="foo, bar">...< /shiro:hasAnyRoles> | 判断当前用户是否具有任意一种角色(foo 或 bar |
<shiro:hasPermission name="foo">...</shiro:hasPermission> | 判断当前用户是否具有某种权限 |
<shiro:lacksPermission name="foo">...</shiro:lacksPermission> | 判断当前用户是否缺少某种权限 |