Spring Security 强制退出指定用户的方法
作者:Anoyi 发布时间:2022-10-04 18:13:04
标签:Spring,Security,强制退出
应用场景
最近社区总有人发文章带上小广告,严重影响社区氛围,好气!对于这种类型的用户,就该永久拉黑!
社区的安全框架使用了 spring-security 和 spring-session,登录状态 30 天有效,session 信息是存在 redis 中,如何优雅地处理这些不老实的用户呢?
首先,简单划分下用户的权限:
管理员(ROLE_MANAGER):基本操作 + 管理操作
普通用户(ROLE_USER):基本操作
拉黑用户(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() 的返回值。
来源:https://www.jianshu.com/p/7766e0b9d98f


猜你喜欢
- 本文实例为大家分享了Android自定义ViewGroup多行多列的具体代码,供大家参考,具体内容如下先看下效果图每行两个子孩子每行一个子孩
- Android中操作Excel文件导出报表时主要采用开源库jxl,最早用在java上,但也可用于Android。与之类似的POI,因为依赖库
- 前言我们利用printf 函数实现一个在屏幕上弹跳的小球,如图所示。弹跳的小球游戏比较简单、容易入门,也是反弹球消砖块、接金币、台球等很多游
- 无聊逛论坛,发现了这张图真是厉害啊,这排序, 既有多线程,又有排序,还有lambda表达式,但是这是C#版本,作为一个入坑的Java爱好者,
- 一、前台服务的简单介绍前台服务是那些被认为用户知道且在系统内存不足的时候不允许系统杀死的服务。前台服务必须给状态栏提供一个通知,它被放到正在
- Android自定义View实现等级滑动条的实例实现效果图:思路: 首先绘制直线,然后等分直线绘制点; 绘制点的时候把X值存到集
- 最近我在考虑如何远程控制tomcat的启动和关机,最后是有友好的界面,能够实现一键式操作的,这样会肯定是会很方便的,网上找了半天,没找到,有
- 主内存和工作内存Java 内存模型规定了所有的变量都存储在主内存中, 每条线程有自己的工作内存线程的工作内存中保存了被该线程使用的变量的主内
- 前言很久没有写关于 Spring 的文章了,最近在系统梳理 Dubbo 代码的过程中发现了 XML schema 这个被遗漏的知识点。由于工
- Feature: 点击选择拍照或者打开相册,选取图片进行裁剪最后设置为圆形头像。Problem: 拍好照片,点击裁剪,弹Toast“无法加载
- 本文实例讲述了Android编程判断当前应用是否在后台运行的方法。分享给大家供大家参考,具体如下:/** 判断程序是否在后台运行 */pub
- 一、概念哈希算法(hash algorithm):是一种将任意内容的输入转换成相同长度输出的加密方式,其输出被称为哈希值。哈希表(hash
- 面试题1:说说你对消息队列的理解,消息队列为了解决什么问题?我们公司业务系统一开始体量较小,很多组件都是单机版就足够,后来随着用户量逐渐扩大
- 使用Javamail发送邮件,必需的jar包(请下载javamail的源文件,官方下载页:http://www.oracle.com/tec
- 相信大家都遇到过,自己的Java应用运行一段时间就宕机了或者响应请求特别慢。这时候就需要我们了来找出问题所在了。绝大部分都是代码问题导致的。
- package cn.mypic; import java.io.Buffe
- 一、 lib文件的简介.lib是一种文件后缀,是Windows操作系统的库文件,有静态lib和动态lib之分:1)、静态lib文件
- 一、短信登录验证机制原理分析了解短信验证码的登陆机制之前,我们首先是要了解用户账号密码登陆的机制是如何的,我们来简要分析一下Spring S
- 在项目开发上,hibernate提供的经验简化了不少工作量和兼容性,但这些绝对需要有经验后才能明白,对于新手来说使用起来很困难。hibern
- 1.springboot启动过程中,首先会收集需要加载的bean的定义,作为BeanDefinition对象,添加到BeanFactory中