Spring Security 强制退出指定用户的方法

 更新时间:2018年03月09日 11:46:14   作者:Anoyi  
本篇文章主要介绍了Spring Security 强制退出指定用户的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

应用场景

最近社区总有人发文章带上小广告,严重影响社区氛围,好气!对于这种类型的用户,就该永久拉黑!

社区的安全框架使用了 spring-security 和 spring-session,登录状态 30 天有效,session 信息是存在 redis 中,如何优雅地处理这些不老实的用户呢?

首先,简单划分下用户的权限:

  1. 管理员(ROLE_MANAGER):基本操作 + 管理操作
  2. 普通用户(ROLE_USER):基本操作
  3. 拉黑用户(ROLE_BLACK):不允许登录

然后,拉黑指定用户(ROLE_USER -> ROLE_BLACK),再强制该用户退出即可(删除该用户在 redis 中 session 信息)。

项目相关依赖及配置

Maven 依赖

    <!-- 安全 Security -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-security</artifactId>
    </dependency>

    <!-- Redis -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>

    <!-- Spring Session Redis -->
    <dependency>
      <groupId>org.springframework.session</groupId>
      <artifactId>spring-session-data-redis</artifactId>
    </dependency>

Spring Session 策略配置 application.yml

# 此处省略 redis 连接相关配置
spring:
 session:
  store-type: redis

Spring Security 配置代码示例

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
        .antMatchers("/user/**").authenticated()
        .antMatchers("/manager/**").hasAnyRole(RoleEnum.MANAGER.getMessage())
        .anyRequest().permitAll()
        .and().formLogin().loginPage("/login").permitAll()
        .and().logout().permitAll()
        .and().csrf().disable();
  }

}

强制退出指定给用户接口

import com.spring4all.bean.ResponseBean;
import com.spring4all.service.UserService;
import lombok.AllArgsConstructor;
import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.session.Session;
import org.springframework.session.data.redis.RedisOperationsSessionRepository;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@RestController
@AllArgsConstructor
public class UserManageApi {

  private final FindByIndexNameSessionRepository<? extends Session> sessionRepository;

  private final RedisOperationsSessionRepository redisOperationsSessionRepository;

  private final UserService userService;

  /**
   * 管理指定用户退出登录
   * @param userId 用户ID
   * @return 用户 Session 信息
   */
  @PreAuthorize("hasRole('MANAGER')")
  @GetMapping("/manager/logout/{userId}")
  public ResponseBean data(@PathVariable() Long userId){
    // 查询 PrincipalNameIndexName(Redis 用户信息的 key),结合自身业务逻辑来实现
    String indexName = userService.getPrincipalNameIndexName(userId);
    // 查询用户的 Session 信息,返回值 key 为 sessionId
    Map<String, ? extends Session> userSessions = sessionRepository.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, indexName);
    // 移除用户的 session 信息
    List<String> sessionIds = new ArrayList<>(userSessions.keySet());
    for (String session : sessionIds) {
      redisOperationsSessionRepository.deleteById(session);
    }
    return ResponseBean.success(userSessions);
  }
}

说明 indexName 为 Principal.getName() 的返回值。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • Nebula Graph介绍和SpringBoot环境连接和查询操作

    Nebula Graph介绍和SpringBoot环境连接和查询操作

    Nebula Graph 是一款开源的、分布式的、易扩展的原生图数据库,能够承载包含数千亿个点和数万亿条边的超大规模数据集,并且提供毫秒级查询,这篇文章主要介绍了Nebula Graph介绍和SpringBoot环境连接和查询,需要的朋友可以参考下
    2022-10-10
  • Spring Data JPA+kkpager实现分页功能实例

    Spring Data JPA+kkpager实现分页功能实例

    本篇文章主要介绍了Spring Data JPA+kkpager实现分页功能实例,具有一定的参考价值,有兴趣的可以了解一下
    2017-06-06
  • java 中DH的方式实现非对称加密的实例

    java 中DH的方式实现非对称加密的实例

    这篇文章主要介绍了java 中DH的方式实现非对称加密的实例的相关资料,这里提供实现简单实例,需要的朋友可以参考下
    2017-08-08
  • 基于Spring的注解@Qualifier小结

    基于Spring的注解@Qualifier小结

    这篇文章主要介绍了Spring的注解@Qualifier小结,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-08-08
  • 扒一扒 Java 中的枚举类型

    扒一扒 Java 中的枚举类型

    这篇文章主要给大家介绍了Java中枚举类型的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2018-12-12
  • Java I/O流使用示例详解

    Java I/O流使用示例详解

    Java.io 包几乎包含了所有操作输入、输出需要的类。所有这些流类代表了输入源和输出目标。本文将通过示例为大家详细讲讲 I/O流的使用教程,需要的可以参考一下
    2022-08-08
  • SpringBoot之RabbitMQ的使用方法

    SpringBoot之RabbitMQ的使用方法

    这篇文章主要介绍了SpringBoot之RabbitMQ的使用方法,详细的介绍了2种模式,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-12-12
  • Spring Cloud Gateway 服务网关快速实现解析

    Spring Cloud Gateway 服务网关快速实现解析

    这篇文章主要介绍了Spring Cloud Gateway 服务网关快速实现解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-08-08
  • 详解JVM的内存对象介绍[创建和访问]

    详解JVM的内存对象介绍[创建和访问]

    这篇文章主要介绍了JVM的内存对象介绍[创建和访问],文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-03-03
  • Java进阶之高并发核心Selector详解

    Java进阶之高并发核心Selector详解

    前几篇文章介绍了Java高并发的一些基础内容,认识了Channel,Buffer和Selector的基本用法,有了感性认识之后,来看看Selector的底层是如何实现的。,需要的朋友可以参考下
    2021-05-05

最新评论