自定义realm整合
此realm目的根据名字从数据库中拿到密码完成认证,并且查找有什么权限(permission)交给SimpleAuthenticationInfo完成认证
然后交给Authorizztioninfo 把其该有的权限授予即可
继承AuthorizationInfo(授权)
完成认证,String userName = token.getPrincipal().toString();
User currentUser=null;
userService.login(userName);
//设置菜单
currentUser.setMenus(permissionService.findMenuByUser(currentUser.getId()));
//设置权限
currentUser.setPermissions(permissionService.findPermissionByUser(currentUser.getId()));
//遍历权限
for (Permission p : currentUser.getPermissions()) {
System.out.println(p.getName());
//核心是拿到这个info交给授权方
SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(currentUser, currentUser.getPwd(), ByteSource.Util.bytes(currentUser.getSalt()),getName());
完成授权
//得到认证成功的CurrentUser,遍历该用户的permission,加到SimpleAuthorizationInfo中返回info完成认证
User currentUser = (User) principalCollection.getPrimaryPrincipal();
SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
Set<String> permission=new HashSet<String>();
for (Permission p : currentUser.getPermissions()) {
permission.add(p.getPercode());
}
info.addStringPermissions(permission);
controller 只负责与前台客户输入的用户名密码与subject主体匹配,和权限匹配,根据权限跳转到哪里代码如下
public class ShiroController {
//用户登录提交
@RequestMapping("/login")
public String loginsubmit(Model model,HttpServletRequest request){
Subject subject=SecurityUtils.getSubject();
try {
//与客户输入的用户名密码匹配
subject.login(new UsernamePasswordToken(request.getParameter("username"),request.getParameter("password")));
} catch (Exception e) {
String errorMessage=null;
if (e.getClass().getName().equals(IncorrectCredentialsException.class.getName())) {
errorMessage="密码错误";
}else if (e.getClass().getName().equals(UnknownAccountException.class.getName())) {
errorMessage="用户不存在";
}else {
errorMessage=errorMessage.getClass().getName();
}
model.addAttribute("errorMessage",errorMessage);
return "login";
}
return "redirect:/index.do";
}
//系统首页
@RequestMapping("/index")
public ModelAndView index(ModelMap map){
Subject subject=SecurityUtils.getSubject();
User currentUser=(User) subject.getPrincipal();
map.addAttribute("currentUser",currentUser);
return new ModelAndView("index");
}
//根据权限跳转到不同的页面
@RequestMapping("/add")
public String addRole(){
Subject subject=SecurityUtils.getSubject();
boolean flag = subject.isPermitted("role:add");
if (flag) {
//如果有权限跳转到home页面
return "home";
}
//没有权限跳转到这个页面
return "refuse";
}
//登出
@RequestMapping("logout")
public String logout() {
Subject subject = SecurityUtils.getSubject();
subject.logout();
return "redirect:/index.do";
}
}