原博客地址:http://jinnianshilongnian.iteye.com/blog/2018398
根据下载的pdf学习。
开涛shiro教程-第二十一章-授予身份与切换身份(二)
1.回顾上节
在《2017.2.15 开涛shiro教程-第二十一章-授予身份与切换身份(一)table、entity、service、dao 》中,做了这四件事。这只是准备材料,要实现 B 假借 A 的身份进行访问,还需要完成controller部分。
1 table:sys_user_runas
2 entity:UserRunAs
3 service:UserRunAsService、UserRunAsServiceImpl
4 dao:UserRunAsDao、UserRunAsDaoImpl
2.最终效果
(1)涉及到的jsp
(2)页面效果
3.controller
package com.github.zhangkaitao.shiro.chapter21.web.controller; import com.github.zhangkaitao.shiro.chapter21.entity.Organization;
import com.github.zhangkaitao.shiro.chapter21.service.OrganizationService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes; /**
* <p>User: Zhang Kaitao
* <p>Date: 14-2-14
* <p>Version: 1.0
*/
@Controller
@RequestMapping("/organization")
public class OrganizationController { @Autowired
private OrganizationService organizationService; @RequiresPermissions("organization:view")
@RequestMapping(method = RequestMethod.GET)
public String index(Model model) {
return "organization/index";
} @RequiresPermissions("organization:view")
@RequestMapping(value = "/tree", method = RequestMethod.GET)
public String showTree(Model model) {
model.addAttribute("organizationList", organizationService.findAll());
return "organization/tree";
} @RequiresPermissions("organization:create")
@RequestMapping(value = "/{parentId}/appendChild", method = RequestMethod.GET)
public String showAppendChildForm(@PathVariable("parentId") Long parentId, Model model) {
Organization parent = organizationService.findOne(parentId);
model.addAttribute("parent", parent);
Organization child = new Organization();
child.setParentId(parentId);
child.setParentIds(parent.makeSelfAsParentIds());
model.addAttribute("child", child);
model.addAttribute("op", "新增");
return "organization/appendChild";
} @RequiresPermissions("organization:create")
@RequestMapping(value = "/{parentId}/appendChild", method = RequestMethod.POST)
public String create(Organization organization) {
organizationService.createOrganization(organization);
return "redirect:/organization/success";
} @RequiresPermissions("organization:update")
@RequestMapping(value = "/{id}/maintain", method = RequestMethod.GET)
public String showMaintainForm(@PathVariable("id") Long id, Model model) {
model.addAttribute("organization", organizationService.findOne(id));
return "organization/maintain";
} @RequiresPermissions("organization:update")
@RequestMapping(value = "/{id}/update", method = RequestMethod.POST)
public String update(Organization organization, RedirectAttributes redirectAttributes) {
organizationService.updateOrganization(organization);
redirectAttributes.addFlashAttribute("msg", "修改成功");
return "redirect:/organization/success";
} @RequiresPermissions("organization:delete")
@RequestMapping(value = "/{id}/delete", method = RequestMethod.POST)
public String delete(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
organizationService.deleteOrganization(id);
redirectAttributes.addFlashAttribute("msg", "删除成功");
return "redirect:/organization/success";
} @RequiresPermissions("organization:update")
@RequestMapping(value = "/{sourceId}/move", method = RequestMethod.GET)
public String showMoveForm(@PathVariable("sourceId") Long sourceId, Model model) {
Organization source = organizationService.findOne(sourceId);
model.addAttribute("source", source);
model.addAttribute("targetList", organizationService.findAllWithExclude(source));
return "organization/move";
} @RequiresPermissions("organization:update")
@RequestMapping(value = "/{sourceId}/move", method = RequestMethod.POST)
public String move(
@PathVariable("sourceId") Long sourceId,
@RequestParam("targetId") Long targetId) {
Organization source = organizationService.findOne(sourceId);
Organization target = organizationService.findOne(targetId);
organizationService.move(source, target);
return "redirect:/organization/success";
} @RequiresPermissions("organization:view")
@RequestMapping(value = "/success", method = RequestMethod.GET)
public String success() {
return "organization/success";
} }
OrganizationController
package com.github.zhangkaitao.shiro.chapter21.web.controller; import com.github.zhangkaitao.shiro.chapter21.entity.Resource;
import com.github.zhangkaitao.shiro.chapter21.service.ResourceService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes; /**
* <p>User: Zhang Kaitao
* <p>Date: 14-2-14
* <p>Version: 1.0
*/
@Controller
@RequestMapping("/resource")
public class ResourceController { @Autowired
private ResourceService resourceService; @ModelAttribute("types")
public Resource.ResourceType[] resourceTypes() {
return Resource.ResourceType.values();
} @RequiresPermissions("resource:view")
@RequestMapping(method = RequestMethod.GET)
public String list(Model model) {
model.addAttribute("resourceList", resourceService.findAll());
return "resource/list";
} @RequiresPermissions("resource:create")
@RequestMapping(value = "/{parentId}/appendChild", method = RequestMethod.GET)
public String showAppendChildForm(@PathVariable("parentId") Long parentId, Model model) {
Resource parent = resourceService.findOne(parentId);
model.addAttribute("parent", parent);
Resource child = new Resource();
child.setParentId(parentId);
child.setParentIds(parent.makeSelfAsParentIds());
model.addAttribute("resource", child);
model.addAttribute("op", "新增子节点");
return "resource/edit";
} @RequiresPermissions("resource:create")
@RequestMapping(value = "/{parentId}/appendChild", method = RequestMethod.POST)
public String create(Resource resource, RedirectAttributes redirectAttributes) {
resourceService.createResource(resource);
redirectAttributes.addFlashAttribute("msg", "新增子节点成功");
return "redirect:/resource";
} @RequiresPermissions("resource:update")
@RequestMapping(value = "/{id}/update", method = RequestMethod.GET)
public String showUpdateForm(@PathVariable("id") Long id, Model model) {
model.addAttribute("resource", resourceService.findOne(id));
model.addAttribute("op", "修改");
return "resource/edit";
} @RequiresPermissions("resource:update")
@RequestMapping(value = "/{id}/update", method = RequestMethod.POST)
public String update(Resource resource, RedirectAttributes redirectAttributes) {
resourceService.updateResource(resource);
redirectAttributes.addFlashAttribute("msg", "修改成功");
return "redirect:/resource";
} @RequiresPermissions("resource:delete")
@RequestMapping(value = "/{id}/delete", method = RequestMethod.GET)
public String delete(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
resourceService.deleteResource(id);
redirectAttributes.addFlashAttribute("msg", "删除成功");
return "redirect:/resource";
} }
ResourceController
package com.github.zhangkaitao.shiro.chapter21.web.controller; import com.github.zhangkaitao.shiro.chapter21.entity.Role;
import com.github.zhangkaitao.shiro.chapter21.service.ResourceService;
import com.github.zhangkaitao.shiro.chapter21.service.RoleService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes; /**
* <p>User: Zhang Kaitao
* <p>Date: 14-2-14
* <p>Version: 1.0
*/
@Controller
@RequestMapping("/role")
public class RoleController { @Autowired
private RoleService roleService; @Autowired
private ResourceService resourceService; @RequiresPermissions("role:view")
@RequestMapping(method = RequestMethod.GET)
public String list(Model model) {
model.addAttribute("roleList", roleService.findAll());
return "role/list";
} @RequiresPermissions("role:create")
@RequestMapping(value = "/create", method = RequestMethod.GET)
public String showCreateForm(Model model) {
setCommonData(model);
model.addAttribute("role", new Role());
model.addAttribute("op", "新增");
return "role/edit";
} @RequiresPermissions("role:create")
@RequestMapping(value = "/create", method = RequestMethod.POST)
public String create(Role role, RedirectAttributes redirectAttributes) {
roleService.createRole(role);
redirectAttributes.addFlashAttribute("msg", "新增成功");
return "redirect:/role";
} @RequiresPermissions("role:update")
@RequestMapping(value = "/{id}/update", method = RequestMethod.GET)
public String showUpdateForm(@PathVariable("id") Long id, Model model) {
setCommonData(model);
model.addAttribute("role", roleService.findOne(id));
model.addAttribute("op", "修改");
return "role/edit";
} @RequiresPermissions("role:update")
@RequestMapping(value = "/{id}/update", method = RequestMethod.POST)
public String update(Role role, RedirectAttributes redirectAttributes) {
roleService.updateRole(role);
redirectAttributes.addFlashAttribute("msg", "修改成功");
return "redirect:/role";
} @RequiresPermissions("role:delete")
@RequestMapping(value = "/{id}/delete", method = RequestMethod.GET)
public String showDeleteForm(@PathVariable("id") Long id, Model model) {
setCommonData(model);
model.addAttribute("role", roleService.findOne(id));
model.addAttribute("op", "删除");
return "role/edit";
} @RequiresPermissions("role:delete")
@RequestMapping(value = "/{id}/delete", method = RequestMethod.POST)
public String delete(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
roleService.deleteRole(id);
redirectAttributes.addFlashAttribute("msg", "删除成功");
return "redirect:/role";
} private void setCommonData(Model model) {
model.addAttribute("resourceList", resourceService.findAll());
} }
RoleController
package com.github.zhangkaitao.shiro.chapter21.web.controller; import com.github.zhangkaitao.shiro.chapter21.entity.User;
import com.github.zhangkaitao.shiro.chapter21.service.*;
import com.github.zhangkaitao.shiro.chapter21.service.RoleService;
import com.github.zhangkaitao.shiro.chapter21.service.UserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes; /**
* <p>User: Zhang Kaitao
* <p>Date: 14-2-14
* <p>Version: 1.0
*/
@Controller
@RequestMapping("/user")
public class UserController { @Autowired
private UserService userService; @Autowired
private OrganizationService organizationService;
@Autowired
private RoleService roleService; @RequiresPermissions("user:view")
@RequestMapping(method = RequestMethod.GET)
public String list(Model model) {
model.addAttribute("userList", userService.findAll());
return "user/list";
} @RequiresPermissions("user:create")
@RequestMapping(value = "/create", method = RequestMethod.GET)
public String showCreateForm(Model model) {
setCommonData(model);
model.addAttribute("user", new User());
model.addAttribute("op", "新增");
return "user/edit";
} @RequiresPermissions("user:create")
@RequestMapping(value = "/create", method = RequestMethod.POST)
public String create(User user, RedirectAttributes redirectAttributes) {
userService.createUser(user);
redirectAttributes.addFlashAttribute("msg", "新增成功");
return "redirect:/user";
} @RequiresPermissions("user:update")
@RequestMapping(value = "/{id}/update", method = RequestMethod.GET)
public String showUpdateForm(@PathVariable("id") Long id, Model model) {
setCommonData(model);
model.addAttribute("user", userService.findOne(id));
model.addAttribute("op", "修改");
return "user/edit";
} @RequiresPermissions("user:update")
@RequestMapping(value = "/{id}/update", method = RequestMethod.POST)
public String update(User user, RedirectAttributes redirectAttributes) {
userService.updateUser(user);
redirectAttributes.addFlashAttribute("msg", "修改成功");
return "redirect:/user";
} @RequiresPermissions("user:delete")
@RequestMapping(value = "/{id}/delete", method = RequestMethod.GET)
public String showDeleteForm(@PathVariable("id") Long id, Model model) {
setCommonData(model);
model.addAttribute("user", userService.findOne(id));
model.addAttribute("op", "删除");
return "user/edit";
} @RequiresPermissions("user:delete")
@RequestMapping(value = "/{id}/delete", method = RequestMethod.POST)
public String delete(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
userService.deleteUser(id);
redirectAttributes.addFlashAttribute("msg", "删除成功");
return "redirect:/user";
} @RequiresPermissions("user:update")
@RequestMapping(value = "/{id}/changePassword", method = RequestMethod.GET)
public String showChangePasswordForm(@PathVariable("id") Long id, Model model) {
model.addAttribute("user", userService.findOne(id));
model.addAttribute("op", "修改密码");
return "user/changePassword";
} @RequiresPermissions("user:update")
@RequestMapping(value = "/{id}/changePassword", method = RequestMethod.POST)
public String changePassword(@PathVariable("id") Long id, String newPassword, RedirectAttributes redirectAttributes) {
userService.changePassword(id, newPassword);
redirectAttributes.addFlashAttribute("msg", "修改密码成功");
return "redirect:/user";
} private void setCommonData(Model model) {
model.addAttribute("organizationList", organizationService.findAll());
model.addAttribute("roleList", roleService.findAll());
}
}
UserController
package com.github.zhangkaitao.shiro.chapter21.web.controller; import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; /**
* <p>User: Zhang Kaitao
* <p>Date: 14-2-15
* <p>Version: 1.0
*/
@Controller
public class LoginController { @RequestMapping(value = "/login" )
public String showLoginForm(HttpServletRequest req, Model model) {
String exceptionClassName = (String)req.getAttribute("shiroLoginFailure");
String error = null;
if(UnknownAccountException.class.getName().equals(exceptionClassName)) {
error = "用户名/密码错误";
} else if(IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {
error = "用户名/密码错误";
} else if(exceptionClassName != null) {
error = "其他错误:" + exceptionClassName;
}
model.addAttribute("error", error);
return "login";
} }
LoginController
package com.github.zhangkaitao.shiro.chapter21.web.controller; import com.github.zhangkaitao.shiro.chapter21.entity.Resource;
import com.github.zhangkaitao.shiro.chapter21.entity.User;
import com.github.zhangkaitao.shiro.chapter21.web.bind.annotation.CurrentUser;
import com.github.zhangkaitao.shiro.chapter21.service.ResourceService;
import com.github.zhangkaitao.shiro.chapter21.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping; import java.util.List;
import java.util.Set; /**
* <p>User: Zhang Kaitao
* <p>Date: 14-2-14
* <p>Version: 1.0
*/
@Controller
public class IndexController { @Autowired
private ResourceService resourceService;
@Autowired
private UserService userService; @RequestMapping("/")
public String index(@CurrentUser User loginUser, Model model) {
Set<String> permissions = userService.findPermissions(loginUser.getUsername());
List<Resource> menus = resourceService.findMenus(permissions);
model.addAttribute("menus", menus);
return "index";
} @RequestMapping("/welcome")
public String welcome() {
return "welcome";
} }
IndexController
RunAsController:
(1)简要总览
四个方法:展示,授予,收回,切换。
@Controller
@RequestMapping("/runas")
public class RunAsController { @Autowired
private UserRunAsService userRunAsService; @Autowired
private UserService userService; @RequestMapping
public String runasList(
@CurrentUser User loginUser,
Model model) {
...
} @RequestMapping("/grant/{toUserId}")
public String grant(
@CurrentUser User loginUser,
@PathVariable("toUserId") Long toUserId,
RedirectAttributes redirectAttributes) {
...
} @RequestMapping("/revoke/{toUserId}")
public String revoke(
@CurrentUser User loginUser,
@PathVariable("toUserId") Long toUserId,
RedirectAttributes redirectAttributes) {
...
} @RequestMapping("/switchTo/{switchToUserId}")
public String switchTo(
@CurrentUser User loginUser,
@PathVariable("switchToUserId") Long switchToUserId,
RedirectAttributes redirectAttributes) {
...
} @RequestMapping("/switchBack")
public String switchBack(RedirectAttributes redirectAttributes) {
...
}
}
(2)runasList
runasList 展示当前用户能切换到的身份列表,及授予给其他人的身份列表。
@RequestMapping
public String runasList(@CurrentUser User loginUser, Model model) {
//fromUserId是A,toUserId是B。
//A:授予别人身份的user(领导),B:被授予身份的user(秘书)
//B可以假借A的身份进行访问 //查询当前用户是不是被授予身份的,并存好
model.addAttribute("fromUserIds", userRunAsService.findFromUserIds(loginUser.getId()));
//查询当前用户有没有授予别人身份,并存好
model.addAttribute("toUserIds", userRunAsService.findToUserIds(loginUser.getId())); //获得除该用户之外的所有users
List<User> allUsers = userService.findAll();
allUsers.remove(loginUser);
model.addAttribute("allUsers", allUsers); Subject subject = SecurityUtils.getSubject();
//subject.isRunAs,用于判定该用户是不是已经是RunAs用户
model.addAttribute("isRunas", subject.isRunAs());
if(subject.isRunAs()) {
//一个用户可以切换很多次身份,之前的身份用栈存储
String previousUsername =
(String)subject.getPreviousPrincipals().getPrimaryPrincipal();
model.addAttribute("previousUsername", previousUsername);
} return "runas";
}
(2)grant
@RequestMapping("/grant/{toUserId}")
public String grant(
@CurrentUser User loginUser,
@PathVariable("toUserId") Long toUserId,
RedirectAttributes redirectAttributes) { if(loginUser.getId().equals(toUserId)) {
redirectAttributes.addFlashAttribute("msg", "自己不能切换到自己的身份");
return "redirect:/runas";
} userRunAsService.grantRunAs(loginUser.getId(), toUserId);
redirectAttributes.addFlashAttribute("msg", "操作成功");
return "redirect:/runas";
}
(3)revoke
@RequestMapping("/revoke/{toUserId}")
public String revoke(
@CurrentUser User loginUser,
@PathVariable("toUserId") Long toUserId,
RedirectAttributes redirectAttributes) {
userRunAsService.revokeRunAs(loginUser.getId(), toUserId);
redirectAttributes.addFlashAttribute("msg", "操作成功");
return "redirect:/runas";
}
(4)switchTo
@RequestMapping("/switchTo/{switchToUserId}")
public String switchTo(
@CurrentUser User loginUser,
@PathVariable("switchToUserId") Long switchToUserId,
RedirectAttributes redirectAttributes) { Subject subject = SecurityUtils.getSubject();
//查找要切换的用户
User switchToUser = userService.findOne(switchToUserId);
if(loginUser.equals(switchToUser)) {
redirectAttributes.addFlashAttribute("msg", "自己不能切换到自己的身份");
return "redirect:/runas";
} //判定能否切换
if(switchToUser == null || !userRunAsService.exists(switchToUserId, loginUser.getId())) {
redirectAttributes.addFlashAttribute("msg", "对方没有授予您身份,不能切换");
return "redirect:/runas";
} //切换身份
subject.runAs(new SimplePrincipalCollection(switchToUser.getUsername(), ""));
redirectAttributes.addFlashAttribute("msg", "操作成功");
redirectAttributes.addFlashAttribute("needRefresh", "true");
return "redirect:/runas";
}
(5)switchBack
要注意的是,数据使用栈数据结构保存的。所以如果A --> B, B-->C, 那么C要调用两次releaseRunAs()才能切换回A。
同样,Subject. getPreviousPrincipals()得到上一次切换到的身份,比如当前是 C;那么调用该 API将得到 B 的身份。
@RequestMapping("/switchBack")
public String switchBack(RedirectAttributes redirectAttributes) { Subject subject = SecurityUtils.getSubject(); if(subject.isRunAs()) {//现在是切换的身份中
//切换至上一个身份
subject.releaseRunAs();
}
redirectAttributes.addFlashAttribute("msg", "操作成功");
redirectAttributes.addFlashAttribute("needRefresh", "true");
return "redirect:/runas";
}
综上可知:
要区分,授予身份与切换身份。
1.A授予身份时
首先判定是不是给自己授予身份
如果不是,就调用这句话:userRunAsService.grantRunAs(loginUser.getId(), toUserId);
而这句话,执行的sql语句是:String sql = "insert into sys_user_runas(from_user_id, to_user_id) values (?,?)";
即它只是在数据库的runas表里插入了一条(A,B)记录。
2.回收身份时,类似,只是删除了一条(A,B)记录。
3.A切换身份至B时
先找到这个要切换的B,确认存在并且不等于A
然后判定B是否被A授予了身份,执行的sql是:String sql = "select count(1) from sys_user_runas where from_user_id=? and to_user_id=?"; 即判定关系(A,B)是否存在。
然后进行身份的切换:subject.runAs(new SimplePrincipalCollection(switchToUser.getUsername(), ""));
4.B切换回A时
先判定这个身份是不是被授予的身份:subject.isRunAs()
然后切换回上一个(从栈数据中拿上一个身份的信息):subject.releaseRunAs();
即,身份的切换是shiro帮我们做好的。我们要做的就是,维护 (fromUserId,toUserId)的关系。换句话说,授予身份由我们完成,切换身份由shiro完成。