SSM整合Shiro-授权案例
接着上一篇登录案例,今天写一篇授权案例,博客结尾有shiro和ssm整合的一整个小案例,完成了登录、授权、缓存和session管理以及RememberMe功能。有需要的小伙伴下载,谢谢。
下面上代码,代码接着上一篇中的修改,我这里主要是授权改动的代码,shiro进行授权是两种方式注解和拦截器,我这里方便起见,使用的是注解。
- 修改自定义Realm
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
//获取身份信息--认证时加入的信息
User user = (User)principal.getPrimaryPrincipal();
//从数据库中查询权限
List<Permission> permissions = userService.getPermission(user);
if (permissions==null||permissions.size()==0){
return null;
}
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
for (Permission p: permissions){
info.addStringPermission(p.getName());
}
return info;
}
2.spring-mvc.xml中配置aop代理以及异常处理
<!-- aop代理-->
<aop:config proxy-target-class="true"/>
<!-- 开启shiro注解支持 -->
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager"/>
</bean>
<!-- 异常处理 -->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<!-- 认证异常 -->
<prop key="org.apache.shiro.authc.AuthenticationException">login</prop>
<!-- 授权异常 -->
<prop key="org.apache.shiro.authz.UnauthorizedException">refuse</prop>
</props>
</property>
</bean>
3.在controller层中添加注解(此处role:update为shiro配置权限的格式,数据库中也是这种格式)
* 修改密码
*/
@RequestMapping("/update")
@RequiresPermissions("role:update")//权限注解
public ModelAndView update(User user){
ModelAndView mav = new ModelAndView("/index");
userService.updatePwd(user);
return mav;
}
4.在jsp中添加按钮权限检查
<%@taglib uri="http://shiro.apache.org/tags" prefix="shiro"%>
<html>
<body>
<h2>Hello World! ${user.username}</h2>
<shiro:hasPermission name="role:update">
<a href="${pageContext.request.contextPath}/user/update?username=${user.username}">修改密码</a>
</shiro:hasPermission>
刚开始写博客,感觉快要坚持不住,昨天学完shiro,今天才写,有点迟了。
加油!