Spring Boot集成Shiro实现动态加载权限的完整步骤

一、前言

本文小编将基于 SpringBoot 集成 Shiro 实现动态uri权限,由前端vue在页面配置uri,Java后端动态刷新权限,不用重启项目,以及在页面分配给用户 角色 、 按钮 、uri 权限后,后端动态分配权限,用户无需在页面重新登录才能获取最新权限,一切权限动态加载,灵活配置

基本环境

  • spring-boot 2.1.7
  • mybatis-plus 2.1.0
  • mysql 5.7.24
  • redis 5.0.5

温馨小提示:案例demo源码附文章末尾,有需要的小伙伴们可参考哦 ~

二、SpringBoot集成Shiro

1、引入相关maven依赖

<properties>
 <shiro-spring.version>1.4.0</shiro-spring.version>
 <shiro-redis.version>3.1.0</shiro-redis.version>
</properties>
<dependencies>
 <!-- AOP依赖,一定要加,否则权限拦截验证不生效 【注:系统日记也需要此依赖】 -->
 <dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-aop</artifactId>
 </dependency>
 <!-- Redis -->
 <dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-data-redis-reactive</artifactId>
 </dependency>
 <!-- Shiro 核心依赖 -->
 <dependency>
 <groupId>org.apache.shiro</groupId>
 <artifactId>shiro-spring</artifactId>
 <version>${shiro-spring.version}</version>
 </dependency>
 <!-- Shiro-redis插件 -->
 <dependency>
 <groupId>org.crazycake</groupId>
 <artifactId>shiro-redis</artifactId>
 <version>${shiro-redis.version}</version>
 </dependency>
</dependencies>

2、自定义Realm

  • doGetAuthenticationInfo:身份认证 (主要是在登录时的逻辑处理)
  • doGetAuthorizationInfo:登陆认证成功后的处理 ex: 赋予角色和权限
    【 注:用户进行权限验证时 Shiro会去缓存中找,如果查不到数据,会执行doGetAuthorizationInfo这个方法去查权限,并放入缓存中 】 -> 因此我们在前端页面分配用户权限时 执行清除shiro缓存的方法即可实现动态分配用户权限
@Slf4j
public class ShiroRealm extends AuthorizingRealm {

 @Autowired
 private UserMapper userMapper;
 @Autowired
 private MenuMapper menuMapper;
 @Autowired
 private RoleMapper roleMapper;

 @Override
 public String getName() {
 return "shiroRealm";
 }

 /**
 * 赋予角色和权限:用户进行权限验证时 Shiro会去缓存中找,如果查不到数据,会执行这个方法去查权限,并放入缓存中
 */
 @Override
 protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
 SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
 // 获取用户
 User user = (User) principalCollection.getPrimaryPrincipal();
 Integer userId =user.getId();
 // 这里可以进行授权和处理
 Set<String> rolesSet = new HashSet<>();
 Set<String> permsSet = new HashSet<>();
 // 获取当前用户对应的权限(这里根据业务自行查询)
 List<Role> roleList = roleMapper.selectRoleByUserId( userId );
 for (Role role:roleList) {
  rolesSet.add( role.getCode() );
  List<Menu> menuList = menuMapper.selectMenuByRoleId( role.getId() );
  for (Menu menu :menuList) {
  permsSet.add( menu.getResources() );
  }
 }
 //将查到的权限和角色分别传入authorizationInfo中
 authorizationInfo.setStringPermissions(permsSet);
 authorizationInfo.setRoles(rolesSet);
 log.info("--------------- 赋予角色和权限成功! ---------------");
 return authorizationInfo;
 }

 /**
 * 身份认证 - 之后走上面的 授权
 */
 @Override
 protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
 UsernamePasswordToken tokenInfo = (UsernamePasswordToken)authenticationToken;
 // 获取用户输入的账号
 String username = tokenInfo.getUsername();
 // 获取用户输入的密码
 String password = String.valueOf( tokenInfo.getPassword() );

 // 通过username从数据库中查找 User对象,如果找到进行验证
 // 实际项目中,这里可以根据实际情况做缓存,如果不做,Shiro自己也是有时间间隔机制,2分钟内不会重复执行该方法
 User user = userMapper.selectUserByUsername(username);
 // 判断账号是否存在
 if (user == null) {
  //返回null -> shiro就会知道这是用户不存在的异常
  return null;
 }
 // 验证密码 【注:这里不采用shiro自身密码验证 , 采用的话会导致用户登录密码错误时,已登录的账号也会自动下线! 如果采用,移除下面的清除缓存到登录处 处理】
 if ( !password.equals( user.getPwd() ) ){
  throw new IncorrectCredentialsException("用户名或者密码错误");
 }

 // 判断账号是否被冻结
 if (user.getFlag()==null|| "0".equals(user.getFlag())){
  throw new LockedAccountException();
 }
 /**
  * 进行验证 -> 注:shiro会自动验证密码
  * 参数1:principal -> 放对象就可以在页面任意地方拿到该对象里面的值
  * 参数2:hashedCredentials -> 密码
  * 参数3:credentialsSalt -> 设置盐值
  * 参数4:realmName -> 自定义的Realm
  */
 SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user, user.getPassword(), ByteSource.Util.bytes(user.getSalt()), getName());
 // 验证成功开始踢人(清除缓存和Session)
 ShiroUtils.deleteCache(username,true);

 // 认证成功后更新token
 String token = ShiroUtils.getSession().getId().toString();
 user.setToken( token );
 userMapper.updateById(user);
 return authenticationInfo;
 }

}

3、Shiro配置类

@Configuration
public class ShiroConfig {

 private final String CACHE_KEY = "shiro:cache:";
 private final String SESSION_KEY = "shiro:session:";
 /**
 * 默认过期时间30分钟,即在30分钟内不进行操作则清空缓存信息,页面即会提醒重新登录
 */
 private final int EXPIRE = 1800;

 /**
 * Redis配置
 */
 @Value("${spring.redis.host}")
 private String host;
 @Value("${spring.redis.port}")
 private int port;
 @Value("${spring.redis.timeout}")
 private int timeout;
// @Value("${spring.redis.password}")
// private String password;

 /**
 * 开启Shiro-aop注解支持:使用代理方式所以需要开启代码支持
 */
 @Bean
 public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
 AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
 authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
 return authorizationAttributeSourceAdvisor;
 }

 /**
 * Shiro基础配置
 */
 @Bean
 public ShiroFilterFactoryBean shiroFilterFactory(SecurityManager securityManager, ShiroServiceImpl shiroConfig){
 ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
 shiroFilterFactoryBean.setSecurityManager(securityManager);

 // 自定义过滤器
 Map<String, Filter> filtersMap = new LinkedHashMap<>();
 // 定义过滤器名称 【注:map里面key值对于的value要为authc才能使用自定义的过滤器】
 filtersMap.put( "zqPerms", new MyPermissionsAuthorizationFilter() );
 filtersMap.put( "zqRoles", new MyRolesAuthorizationFilter() );
 filtersMap.put( "token", new TokenCheckFilter() );
 shiroFilterFactoryBean.setFilters(filtersMap);

 // 登录的路径: 如果你没有登录则会跳到这个页面中 - 如果没有设置值则会默认跳转到工程根目录下的"/login.jsp"页面 或 "/login" 映射
 shiroFilterFactoryBean.setLoginUrl("/api/auth/unLogin");
 // 登录成功后跳转的主页面 (这里没用,前端vue控制了跳转)
// shiroFilterFactoryBean.setSuccessUrl("/index");
 // 设置没有权限时跳转的url
 shiroFilterFactoryBean.setUnauthorizedUrl("/api/auth/unauth");

 shiroFilterFactoryBean.setFilterChainDefinitionMap( shiroConfig.loadFilterChainDefinitionMap() );
 return shiroFilterFactoryBean;
 }

 /**
 * 安全管理器
 */
 @Bean
 public SecurityManager securityManager() {
 DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
 // 自定义session管理
 securityManager.setSessionManager(sessionManager());
 // 自定义Cache实现缓存管理
 securityManager.setCacheManager(cacheManager());
 // 自定义Realm验证
 securityManager.setRealm(shiroRealm());
 return securityManager;
 }

 /**
 * 身份验证器
 */
 @Bean
 public ShiroRealm shiroRealm() {
 ShiroRealm shiroRealm = new ShiroRealm();
 shiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());
 return shiroRealm;
 }

 /**
 * 自定义Realm的加密规则 -> 凭证匹配器:将密码校验交给Shiro的SimpleAuthenticationInfo进行处理,在这里做匹配配置
 */
 @Bean
 public HashedCredentialsMatcher hashedCredentialsMatcher() {
 HashedCredentialsMatcher shaCredentialsMatcher = new HashedCredentialsMatcher();
 // 散列算法:这里使用SHA256算法;
 shaCredentialsMatcher.setHashAlgorithmName(SHA256Util.HASH_ALGORITHM_NAME);
 // 散列的次数,比如散列两次,相当于 md5(md5(""));
 shaCredentialsMatcher.setHashIterations(SHA256Util.HASH_ITERATIONS);
 return shaCredentialsMatcher;
 }

 /**
 * 配置Redis管理器:使用的是shiro-redis开源插件
 */
 @Bean
 public RedisManager redisManager() {
 RedisManager redisManager = new RedisManager();
 redisManager.setHost(host);
 redisManager.setPort(port);
 redisManager.setTimeout(timeout);
// redisManager.setPassword(password);
 return redisManager;
 }

 /**
 * 配置Cache管理器:用于往Redis存储权限和角色标识 (使用的是shiro-redis开源插件)
 */
 @Bean
 public RedisCacheManager cacheManager() {
 RedisCacheManager redisCacheManager = new RedisCacheManager();
 redisCacheManager.setRedisManager(redisManager());
 redisCacheManager.setKeyPrefix(CACHE_KEY);
 // 配置缓存的话要求放在session里面的实体类必须有个id标识 注:这里id为用户表中的主键,否-> 报:User must has getter for field: xx
 redisCacheManager.setPrincipalIdFieldName("id");
 return redisCacheManager;
 }

 /**
 * SessionID生成器
 */
 @Bean
 public ShiroSessionIdGenerator sessionIdGenerator(){
 return new ShiroSessionIdGenerator();
 }

 /**
 * 配置RedisSessionDAO (使用的是shiro-redis开源插件)
 */
 @Bean
 public RedisSessionDAO redisSessionDAO() {
 RedisSessionDAO redisSessionDAO = new RedisSessionDAO();
 redisSessionDAO.setRedisManager(redisManager());
 redisSessionDAO.setSessionIdGenerator(sessionIdGenerator());
 redisSessionDAO.setKeyPrefix(SESSION_KEY);
 redisSessionDAO.setExpire(EXPIRE);
 return redisSessionDAO;
 }

 /**
 * 配置Session管理器
 */
 @Bean
 public SessionManager sessionManager() {
 ShiroSessionManager shiroSessionManager = new ShiroSessionManager();
 shiroSessionManager.setSessionDAO(redisSessionDAO());
 return shiroSessionManager;
 }

}

三、shiro动态加载权限处理方法

  1. loadFilterChainDefinitionMap:初始化权限
    ex: 在上面Shiro配置类ShiroConfig中的Shiro基础配置shiroFilterFactory方法中我们就需要调用此方法将数据库中配置的所有uri权限全部加载进去,以及放行接口和配置权限过滤器等
    【注:过滤器配置顺序不能颠倒,多个过滤器用,分割】
    ex: filterChainDefinitionMap.put("/api/system/user/list", "authc,token,zqPerms[user1]")
  2. updatePermission:动态刷新加载数据库中的uri权限 -> 页面在新增uri路径到数据库中,也就是配置新的权限时就可以调用此方法实现动态加载uri权限
  3. updatePermissionByRoleId:shiro动态权限加载 -> 即分配指定用户权限时可调用此方法删除shiro缓存,重新执行doGetAuthorizationInfo方法授权角色和权限
public interface ShiroService {

 /**
 * 初始化权限 -> 拿全部权限
 *
 * @param :
 * @return: java.util.Map<java.lang.String,java.lang.String>
 */
 Map<String, String> loadFilterChainDefinitionMap();

 /**
 * 在对uri权限进行增删改操作时,需要调用此方法进行动态刷新加载数据库中的uri权限
 *
 * @param shiroFilterFactoryBean
 * @param roleId
 * @param isRemoveSession:
 * @return: void
 */
 void updatePermission(ShiroFilterFactoryBean shiroFilterFactoryBean, Integer roleId, Boolean isRemoveSession);

 /**
 * shiro动态权限加载 -> 原理:删除shiro缓存,重新执行doGetAuthorizationInfo方法授权角色和权限
 *
 * @param roleId
 * @param isRemoveSession:
 * @return: void
 */
 void updatePermissionByRoleId(Integer roleId, Boolean isRemoveSession);

}
@Slf4j
@Service
public class ShiroServiceImpl implements ShiroService {

 @Autowired
 private MenuMapper menuMapper;
 @Autowired
 private UserMapper userMapper;
 @Autowired
 private RoleMapper roleMapper;

 @Override
 public Map<String, String> loadFilterChainDefinitionMap() {
 // 权限控制map
 Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
 // 配置过滤:不会被拦截的链接 -> 放行 start ----------------------------------------------------------
 // 放行Swagger2页面,需要放行这些
 filterChainDefinitionMap.put("/swagger-ui.html","anon");
 filterChainDefinitionMap.put("/swagger/**","anon");
 filterChainDefinitionMap.put("/webjars/**", "anon");
 filterChainDefinitionMap.put("/swagger-resources/**","anon");
 filterChainDefinitionMap.put("/v2/**","anon");
 filterChainDefinitionMap.put("/static/**", "anon");

 // 登陆
 filterChainDefinitionMap.put("/api/auth/login/**", "anon");
 // 三方登录
 filterChainDefinitionMap.put("/api/auth/loginByQQ", "anon");
 filterChainDefinitionMap.put("/api/auth/afterlogin.do", "anon");
 // 退出
 filterChainDefinitionMap.put("/api/auth/logout", "anon");
 // 放行未授权接口,重定向使用
 filterChainDefinitionMap.put("/api/auth/unauth", "anon");
 // token过期接口
 filterChainDefinitionMap.put("/api/auth/tokenExpired", "anon");
 // 被挤下线
 filterChainDefinitionMap.put("/api/auth/downline", "anon");
 // 放行 end ----------------------------------------------------------

 // 从数据库或缓存中查取出来的url与resources对应则不会被拦截 放行
 List<Menu> permissionList = menuMapper.selectList( null );
 if ( !CollectionUtils.isEmpty( permissionList ) ) {
  permissionList.forEach( e -> {
  if ( StringUtils.isNotBlank( e.getUrl() ) ) {
   // 根据url查询相关联的角色名,拼接自定义的角色权限
   List<Role> roleList = roleMapper.selectRoleByMenuId( e.getId() );
   StringJoiner zqRoles = new StringJoiner(",", "zqRoles[", "]");
   if ( !CollectionUtils.isEmpty( roleList ) ){
   roleList.forEach( f -> {
    zqRoles.add( f.getCode() );
   });
   }

   // 注意过滤器配置顺序不能颠倒
   // ① 认证登录
   // ② 认证自定义的token过滤器 - 判断token是否有效
   // ③ 角色权限 zqRoles:自定义的只需要满足其中一个角色即可访问 ; roles[admin,guest] : 默认需要每个参数满足才算通过,相当于hasAllRoles()方法
   // ④ zqPerms:认证自定义的url过滤器拦截权限 【注:多个过滤器用 , 分割】
//   filterChainDefinitionMap.put( "/api" + e.getUrl(),"authc,token,roles[admin,guest],zqPerms[" + e.getResources() + "]" );
   filterChainDefinitionMap.put( "/api" + e.getUrl(),"authc,token,"+ zqRoles.toString() +",zqPerms[" + e.getResources() + "]" );
//   filterChainDefinitionMap.put("/api/system/user/listPage", "authc,token,zqPerms[user1]"); // 写死的一种用法
  }
  });
 }
 // ⑤ 认证登录 【注:map不能存放相同key】
 filterChainDefinitionMap.put("/**", "authc");
 return filterChainDefinitionMap;
 }

 @Override
 public void updatePermission(ShiroFilterFactoryBean shiroFilterFactoryBean, Integer roleId, Boolean isRemoveSession) {
 synchronized (this) {
  AbstractShiroFilter shiroFilter;
  try {
  shiroFilter = (AbstractShiroFilter) shiroFilterFactoryBean.getObject();
  } catch (Exception e) {
  throw new MyException("get ShiroFilter from shiroFilterFactoryBean error!");
  }
  PathMatchingFilterChainResolver filterChainResolver = (PathMatchingFilterChainResolver) shiroFilter.getFilterChainResolver();
  DefaultFilterChainManager manager = (DefaultFilterChainManager) filterChainResolver.getFilterChainManager();

  // 清空拦截管理器中的存储
  manager.getFilterChains().clear();
  // 清空拦截工厂中的存储,如果不清空这里,还会把之前的带进去
  //  ps:如果仅仅是更新的话,可以根据这里的 map 遍历数据修改,重新整理好权限再一起添加
  shiroFilterFactoryBean.getFilterChainDefinitionMap().clear();
  // 动态查询数据库中所有权限
  shiroFilterFactoryBean.setFilterChainDefinitionMap(loadFilterChainDefinitionMap());
  // 重新构建生成拦截
  Map<String, String> chains = shiroFilterFactoryBean.getFilterChainDefinitionMap();
  for (Map.Entry<String, String> entry : chains.entrySet()) {
  manager.createChain(entry.getKey(), entry.getValue());
  }
  log.info("--------------- 动态生成url权限成功! ---------------");

  // 动态更新该角色相关联的用户shiro权限
  if(roleId != null){
  updatePermissionByRoleId(roleId,isRemoveSession);
  }
 }
 }

 @Override
 public void updatePermissionByRoleId(Integer roleId, Boolean isRemoveSession) {
 // 查询当前角色的用户shiro缓存信息 -> 实现动态权限
 List<User> userList = userMapper.selectUserByRoleId(roleId);
 // 删除当前角色关联的用户缓存信息,用户再次访问接口时会重新授权 ; isRemoveSession为true时删除Session -> 即强制用户退出
 if ( !CollectionUtils.isEmpty( userList ) ) {
  for (User user : userList) {
  ShiroUtils.deleteCache(user.getUsername(), isRemoveSession);
  }
 }
 log.info("--------------- 动态修改用户权限成功! ---------------");
 }

}

四、shiro中自定义角色、权限过滤器

1、自定义uri权限过滤器 zqPerms

@Slf4j
public class MyPermissionsAuthorizationFilter extends PermissionsAuthorizationFilter {

 @Override
 protected boolean onAccessDenied(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
 HttpServletRequest httpRequest = (HttpServletRequest) request;
 HttpServletResponse httpResponse = (HttpServletResponse) response;
 String requestUrl = httpRequest.getServletPath();
 log.info("请求的url: " + requestUrl);

 // 检查是否拥有访问权限
 Subject subject = this.getSubject(request, response);
 if (subject.getPrincipal() == null) {
  this.saveRequestAndRedirectToLogin(request, response);
 } else {
  // 转换成http的请求和响应
  HttpServletRequest req = (HttpServletRequest) request;
  HttpServletResponse resp = (HttpServletResponse) response;

  // 获取请求头的值
  String header = req.getHeader("X-Requested-With");
  // ajax 的请求头里有X-Requested-With: XMLHttpRequest 正常请求没有
  if (header!=null && "XMLHttpRequest".equals(header)){
  resp.setContentType("text/json,charset=UTF-8");
  resp.getWriter().print("{\"success\":false,\"msg\":\"没有权限操作!\"}");
  }else { //正常请求
  String unauthorizedUrl = this.getUnauthorizedUrl();
  if (StringUtils.hasText(unauthorizedUrl)) {
   WebUtils.issueRedirect(request, response, unauthorizedUrl);
  } else {
   WebUtils.toHttp(response).sendError(401);
  }
  }

 }
 return false;
 }
 
}

2、自定义角色权限过滤器 zqRoles

shiro原生的角色过滤器RolesAuthorizationFilter 默认是必须同时满足roles[admin,guest]才有权限,而自定义的zqRoles 只满足其中一个即可访问

ex: zqRoles[admin,guest]

public class MyRolesAuthorizationFilter extends AuthorizationFilter {

 @Override
 protected boolean isAccessAllowed(ServletRequest req, ServletResponse resp, Object mappedValue) throws Exception {
  Subject subject = getSubject(req, resp);
  String[] rolesArray = (String[]) mappedValue;
  // 没有角色限制,有权限访问
  if (rolesArray == null || rolesArray.length == 0) {
   return true;
  }
  for (int i = 0; i < rolesArray.length; i++) {
   //若当前用户是rolesArray中的任何一个,则有权限访问
   if (subject.hasRole(rolesArray[i])) {
    return true;
   }
  }
  return false;
 }

}

3、自定义token过滤器 token -> 判断token是否过期失效等

@Slf4j
public class TokenCheckFilter extends UserFilter {

 /**
  * token过期、失效
  */
 private static final String TOKEN_EXPIRED_URL = "/api/auth/tokenExpired";

 /**
  * 判断是否拥有权限 true:认证成功 false:认证失败
  * mappedValue 访问该url时需要的权限
  * subject.isPermitted 判断访问的用户是否拥有mappedValue权限
  */
 @Override
 public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
  HttpServletRequest httpRequest = (HttpServletRequest) request;
  HttpServletResponse httpResponse = (HttpServletResponse) response;
  // 根据请求头拿到token
  String token = WebUtils.toHttp(request).getHeader(Constants.REQUEST_HEADER);
  log.info("浏览器token:" + token );
  User userInfo = ShiroUtils.getUserInfo();
  String userToken = userInfo.getToken();
  // 检查token是否过期
  if ( !token.equals(userToken) ){
   return false;
  }
  return true;
 }

 /**
  * 认证失败回调的方法: 如果登录实体为null就保存请求和跳转登录页面,否则就跳转无权限配置页面
  */
 @Override
 protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
  User userInfo = ShiroUtils.getUserInfo();
  // 重定向错误提示处理 - 前后端分离情况下
  WebUtils.issueRedirect(request, response, TOKEN_EXPIRED_URL);
  return false;
 }

}

五、项目中会用到的一些工具类、常量等

温馨小提示:这里只是部分,详情可参考文章末尾给出的案例demo源码

1、Shiro工具类

public class ShiroUtils {

 /** 私有构造器 **/
 private ShiroUtils(){ }

 private static RedisSessionDAO redisSessionDAO = SpringUtil.getBean(RedisSessionDAO.class);

 /**
  * 获取当前用户Session
  * @Return SysUserEntity 用户信息
  */
 public static Session getSession() {
  return SecurityUtils.getSubject().getSession();
 }

 /**
  * 用户登出
  */
 public static void logout() {
  SecurityUtils.getSubject().logout();
 }

 /**
  * 获取当前用户信息
  * @Return SysUserEntity 用户信息
  */
 public static User getUserInfo() {
  return (User) SecurityUtils.getSubject().getPrincipal();
 }

 /**
  * 删除用户缓存信息
  * @Param username 用户名称
  * @Param isRemoveSession 是否删除Session,删除后用户需重新登录
  */
 public static void deleteCache(String username, boolean isRemoveSession){
  //从缓存中获取Session
  Session session = null;
  // 获取当前已登录的用户session列表
  Collection<Session> sessions = redisSessionDAO.getActiveSessions();
  User sysUserEntity;
  Object attribute = null;
  // 遍历Session,找到该用户名称对应的Session
  for(Session sessionInfo : sessions){
   attribute = sessionInfo.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
   if (attribute == null) {
    continue;
   }
   sysUserEntity = (User) ((SimplePrincipalCollection) attribute).getPrimaryPrincipal();
   if (sysUserEntity == null) {
    continue;
   }
   if (Objects.equals(sysUserEntity.getUsername(), username)) {
    session=sessionInfo;
    // 清除该用户以前登录时保存的session,强制退出 -> 单用户登录处理
    if (isRemoveSession) {
     redisSessionDAO.delete(session);
    }
   }
  }

  if (session == null||attribute == null) {
   return;
  }
  //删除session
  if (isRemoveSession) {
   redisSessionDAO.delete(session);
  }
  //删除Cache,再访问受限接口时会重新授权
  DefaultWebSecurityManager securityManager = (DefaultWebSecurityManager) SecurityUtils.getSecurityManager();
  Authenticator authc = securityManager.getAuthenticator();
  ((LogoutAware) authc).onLogout((SimplePrincipalCollection) attribute);
 }

 /**
  * 从缓存中获取指定用户名的Session
  * @param username
  */
 private static Session getSessionByUsername(String username){
  // 获取当前已登录的用户session列表
  Collection<Session> sessions = redisSessionDAO.getActiveSessions();
  User user;
  Object attribute;
  // 遍历Session,找到该用户名称对应的Session
  for(Session session : sessions){
   attribute = session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
   if (attribute == null) {
    continue;
   }
   user = (User) ((SimplePrincipalCollection) attribute).getPrimaryPrincipal();
   if (user == null) {
    continue;
   }
   if (Objects.equals(user.getUsername(), username)) {
    return session;
   }
  }
  return null;
 }

}

2、Redis常量类

public interface RedisConstant {
 /**
  * TOKEN前缀
  */
 String REDIS_PREFIX_LOGIN = "code-generator_token_%s";
}

3、Spring上下文工具类

@Component
public class SpringUtil implements ApplicationContextAware {
 private static ApplicationContext context;
 /**
  * Spring在bean初始化后会判断是不是ApplicationContextAware的子类
  * 如果该类是,setApplicationContext()方法,会将容器中ApplicationContext作为参数传入进去
  */
 @Override
 public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
  context = applicationContext;
 }
 /**
  * 通过Name返回指定的Bean
  */
 public static <T> T getBean(Class<T> beanClass) {
  return context.getBean(beanClass);
 }
}

六、案例demo源码

GitHub地址

https://github.com/zhengqingya/code-generator/tree/master/code-generator-api/src/main/java/com/zhengqing/modules/shiro

码云地址

https://gitee.com/zhengqingya/code-generator/blob/master/code-generator-api/src/main/java/com/zhengqing/modules/shiro

本地下载

http://xiazai.jb51.net/201909/yuanma/code-generator(jb51net).rar

总结

以上就是我在处理客户端真实IP的方法,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对呐喊教程的支持。

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。