package com.bcxin.sp.shiro.realm; import com.bcxin.sp.config.exception.BusinessException; import com.bcxin.sp.shiro.service.SysLoginService; import com.bcxin.sp.work.entity.domain.user.User; import com.bcxin.sp.work.util.ShiroUtils; import org.apache.shiro.authc.*; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.cache.Cache; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.subject.SimplePrincipalCollection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Resource; import java.util.HashSet; import java.util.Set; /** * 自定义Realm 处理登录 权限 * * @author task */ public class UserRealm extends AuthorizingRealm { private static final Logger log = LoggerFactory.getLogger(UserRealm.class); @Resource private SysLoginService loginService; /** * 授权 */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) { User user = ShiroUtils.getSysUser(); // // 角色列表 // Set roles = new HashSet(); // // 功能列表 // Set menus = new HashSet(); SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); // // 管理员拥有所有权限 // if (user.isAdmin()) // { info.addRole("admin"); info.addStringPermission("*:*:*"); // } // else // { // roles = roleService.selectRoleKeys(user.getUserId()); // menus = menuService.selectPermsByUserId(user.getUserId()); // // 角色加入AuthorizationInfo认证对象 // info.setRoles(roles); // // 权限加入AuthorizationInfo认证对象 // info.setStringPermissions(menus); // } return info; } /** * 登录认证 */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { UsernamePasswordToken upToken = (UsernamePasswordToken) token; String username = upToken.getUsername(); String password = ""; if (upToken.getPassword() != null) { password = new String(upToken.getPassword()); } User user = null; try { user = loginService.login(username, password); } catch (BusinessException e) { log.info("****对用户[" + username + "]进行登录验证..验证未通过{}", e.getMessage()); throw new AuthenticationException(e.getMessage(), e); } catch (Exception e) { log.info("对用户[" + username + "]进行登录验证..验证未通过{}", e.getMessage()); throw new AuthenticationException(e.getMessage(), e); } SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName()); return info; } /** * 清理指定用户授权信息缓存 */ public void clearCachedAuthorizationInfo(Object principal) { SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName()); this.clearCachedAuthorizationInfo(principals); } /** * 清理所有用户授权信息缓存 */ public void clearAllCachedAuthorizationInfo() { Cache cache = getAuthorizationCache(); if (cache != null) { for (Object key : cache.keys()) { cache.remove(key); } } } }