/** 设定Password校验的Hash算法与迭代次数. */ @PostConstruct public void initCredentialsMatcher() { HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(shiroUserService.getHashAlgorithm()); matcher.setHashIterations(shiroUserService.getHashInterations()); setCredentialsMatcher(matcher); }
/** 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用. */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { System.out.println("=========================doGetAuthorizationInfo"); ShiroUser shiroUser = (ShiroUser) principals.getPrimaryPrincipal(); ShiroUser user = shiroUserService.findUserByLoginName(shiroUser.getUsername()); SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); List<ShiroRole> roles = user.getRoleList(); // 用户角色 List<ShiroPermission> permissions = user.getPermissionList(); // 用户权限 if (roles != null) { for (ShiroRole role : roles) { // 基于Role的权限信息 info.addRole(role.getRoleName()); // 基于角色Permission的权限信息 List<ShiroPermission> rolePermissions = role.getPermissionList(); if (rolePermissions != null) { for (ShiroPermission permission : rolePermissions) { info.addStringPermission(permission.getPermissionName()); } } } } if (permissions != null) { for (ShiroPermission permission : permissions) { // 基于用户Permission的权限信息 info.addStringPermission(permission.getPermissionName()); } } // TODO:删除,测试用代码 info.addRole("root"); info.addStringPermission("user:edit"); info.addStringPermission("user:list"); return info; }
/** 认证回调函数,登录时调用. */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AccountException { Subject currentUser = SecurityUtils.getSubject(); currentUser.getSession(); System.out.println("============" + this.getAuthenticationCacheName()); System.out.println("============" + this.getAuthorizationCacheName()); UsernamePasswordToken token = (UsernamePasswordToken) authcToken; ShiroUser user = null; try { user = shiroUserService.findUserByLoginName(token.getUsername()); } catch (Exception e) { e.printStackTrace(); } if (user != null) { if (!user.isEnabled()) { throw new DisabledAccountException(); } byte[] salt = EncodeUtils.hexDecode(user.getSalt()); return new SimpleAuthenticationInfo( user, user.getPassword(), ByteSource.Util.bytes(salt), getName()); } else { return null; } }