1、修改ShiroDbRealm類,實現它的doGetAuthorizationInfo方法html
package org.shiro.demo.service.realm; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import org.apache.commons.lang.StringUtils; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.authz.AuthorizationException; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.shiro.demo.entity.Permission; import org.shiro.demo.entity.Role; import org.shiro.demo.entity.User; import org.shiro.demo.service.IUserService; public class ShiroDbRealm extends AuthorizingRealm{ @Resource(name="userService") private IUserService userService; protected AuthorizationInfo doGetAuthorizationInfo( PrincipalCollection principals) { SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); //獲取當前登陸的用戶名 String account = (String) super.getAvailablePrincipal(principals); List<String> roles = new ArrayList<String>(); List<String> permissions = new ArrayList<String>(); User user = userService.getByAccount(account); if(user != null){ if (user.getRoles() != null && user.getRoles().size() > 0) { for (Role role : user.getRoles()) { roles.add(role.getName()); if (role.getPmss() != null && role.getPmss().size() > 0) { for (Permission pmss : role.getPmss()) { if(!StringUtils.isEmpty(pmss.getPermission())){ permissions.add(pmss.getPermission()); } } } } } }else{ throw new AuthorizationException(); } //給當前用戶設置角色 info.addRoles(roles); //給當前用戶設置權限 info.addStringPermissions(permissions); return info; } /** * 認證回調函數,登陸時調用. */ protected AuthenticationInfo doGetAuthenticationInfo( AuthenticationToken authcToken) throws AuthenticationException { UsernamePasswordToken token = (UsernamePasswordToken) authcToken; User user = userService.getByAccount(token.getUsername()); if (user != null) { return new SimpleAuthenticationInfo(user.getAccount(), user .getPassword(), user.getNickname()); } else { return null; } } }
其實代碼邏輯很簡單,不過就是從principals獲取當前用戶名,而後讀取user的role及permission信息。理解下就知道了。java
2、初始化系統用戶信息,利用Shiro Annotation實現權限認證。web
(一)新建testInitSystemData junit測試類。(本着快速測試的目的,咱們利用spring junit測試來初始化數據!o(╯□╰)o)spring
package org.shiro.demo.junit; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import org.junit.Test; import org.junit.runner.RunWith; import org.shiro.demo.entity.Permission; import org.shiro.demo.entity.Role; import org.shiro.demo.entity.User; import org.shiro.demo.service.IBaseService; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.transaction.TransactionConfiguration; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:applicationContext.xml","classpath:spring-mvc.xml"}) @TransactionConfiguration(transactionManager="txManager",defaultRollback=false) public class testInitSystemData extends AbstractTransactionalJUnit4SpringContextTests{ @Resource(name="baseService") private IBaseService baseService; @Test public void initPermission() throws Exception{ List<Permission> list = new ArrayList<Permission>(); Permission pmss1 = new Permission(); pmss1.setName("新建用戶"); pmss1.setDescription("新建用戶"); pmss1.setPermission("user:create"); Permission pmss2 = new Permission(); pmss2.setName("編輯用戶"); pmss2.setDescription("編輯用戶"); pmss2.setPermission("user:edit"); Permission pmss3 = new Permission(); pmss3.setName("刪除用戶"); pmss3.setDescription("刪除用戶"); pmss3.setPermission("user:delete"); Permission pmss4 = new Permission(); pmss4.setName("審覈用戶"); pmss4.setDescription("審覈用戶"); pmss4.setPermission("user:audit"); list.add(pmss1); list.add(pmss2); list.add(pmss3); list.add(pmss4); for(Permission pms : list){ baseService.save(pms); } } @Test public void initAdminRole() throws Exception{ List<Permission> list = new ArrayList<Permission>(); list = (List<Permission>)baseService.getAll(Permission.class); Role role = new Role(); role.setName("administrator"); role.setDescription("系統管理員角色"); role.setPmss(list); baseService.save(role); } @Test public void initAdminUser(){ List<Role> list = new ArrayList<Role>(); String jpql = "from Role as o where o.name=?"; list = baseService.getByJpql(jpql, "administrator"); User user = new User(); user.setAccount("admin"); user.setPassword("123456"); user.setNickname("july"); user.setRoles(list); baseService.save(user); } }
(二)新建UserController類,新建用戶註冊頁,並給用戶註冊上加上shiro權限驗證,要求用戶必須具有administrator角色apache
UserController.javaspring-mvc
package org.shiro.demo.controller; import javax.annotation.Resource; import org.apache.shiro.authz.annotation.RequiresRoles; import org.shiro.demo.entity.User; import org.shiro.demo.service.IUserService; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping(value = "/user") public class UserController { @Resource(name="userService") private IUserService userService; @RequestMapping(value = "/register",method=RequestMethod.POST) @ResponseBody @RequiresRoles("administrator") public boolean register(User user){ return userService.register(user); } }
@RequiresRoles("administrator")就是咱們使用的Shirro註解了。mvc
register.jspapp
<%@ page language="java" pageEncoding="utf-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>shirodemo register page</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> </head> <body> <form action="<%=basePath%>/user/register" method="post"> <ul> <li>姓 名:<input type="text" name="account" /> </li> <li>密 碼:<input type="text" name="password" /> </li> <li>暱 稱:<input type="text" name="nickname" /> </li> <li><input type="submit" value="確認" /> </li> </ul> </form> </body> </html>