当前位置: 首页 > news >正文

Spring Security 实现后台切换用户

Spring Security version 

后端代码:


/*** @author Jerry* @date 2024-03-28 17:47* spring security 切换账号*/@RestController
@RequiredArgsConstructor
@RequestMapping("api/admin")
public class AccountSwitchController {private final UserDetailsService userDetailsService;private final TokenComponent tokenComponent;private final SystemAdminService systemAdminService;@PostMapping("/switchAccount")public CommonResult<SystemLoginResponse> switchAccount(@RequestParam String username) {// 当前登录用户是否是超级管理员LoginUserVo loginUserVo = tokenComponent.getLoginUser(ServletUtils.getRequest());if (loginUserVo == null || loginUserVo.getUser().getId() != 1) {throw new TGOException("非法请求");}Authentication auth = SecurityContextHolder.getContext().getAuthentication();UserDetails targetUser = userDetailsService.loadUserByUsername(username);// 创建一个新的Authentication对象,使用目标用户的详情Authentication newAuth = new UsernamePasswordAuthenticationToken(targetUser, auth.getCredentials(), auth.getAuthorities());// 更新SecurityContextHolder中的认证信息SecurityContextHolder.getContext().setAuthentication(newAuth);LoginUserVo loginUser = (LoginUserVo) newAuth.getPrincipal();SystemAdmin systemAdmin = loginUser.getUser();String token = tokenComponent.createToken(loginUser);SystemLoginResponse systemAdminResponse = new SystemLoginResponse();systemAdminResponse.setToken(token);BeanUtils.copyProperties(systemAdmin, systemAdminResponse);//更新最后登录信息systemAdmin.setLoginCount(systemAdmin.getLoginCount() + 1);systemAdminService.updateById(systemAdmin);// 可以重定向到一个页面,以便更新页面上的用户信息return CommonResult.success(systemAdminResponse, "login success");}
}

 前端代码:

效果:

http://www.lryc.cn/news/331866.html

相关文章:

  • 《QT实用小工具·一》电池电量组件
  • 基于springboot实现墙绘产品展示交易平台管理系统项目【项目源码+论文说明】计算机毕业设计
  • 主流公链文章整理
  • css3之3D转换transform
  • SpringBoot -- 外部化配置
  • 优酷动漫顶梁柱!神话大乱炖的修仙番为何火爆?
  • 每日一题:C语言经典例题之判断实数相等
  • 【算法每日一练]-数论(保姆级教程 篇1 埃氏筛,欧拉筛)
  • 【剑指offr--C/C++】JZ59 滑动窗口的最大值
  • RabbitMQ Tutorial
  • 如何对Webpack进行优化
  • nut-ui中的menu 菜单组件的二次封装
  • python笔记(11)序列
  • Rust egui(4) 增加自己的tab页面
  • 小组分享第二部分:Jsoup
  • C#(winform) 调用MATLAB函数
  • Kubernetes探索-Pod面试(补充)
  • 深入了解JUnit 5:新一代Java单元测试框架
  • 2024年清明节安装matlab 2024a
  • 关于PostgreSQL JDBC中的log输出是怎么回事?
  • 【科研笔记】知识星球不可选择内容爬虫
  • [技术闲聊]我对电路设计的理解(二)
  • 【Android、 kotlin】kotlin学习笔记
  • Debian 配置国内软件源
  • 选数(dfs,isprime)
  • RocketMQ(版本4.9.4)+RocketMQ_Dashbord环境搭建(生产者、消费者的前置环境搭建)
  • css隐藏溢出隐藏的滚动条
  • scss常用混入(mixin)、@inclue
  • 补代码随想录算法训练营第44天 | 完全背包、518. 零钱兑换 II 、377. 组合总和 Ⅳ
  • 【Linux】网络基础常识{OSI七层模型/ TCP/IP / 端口号 /各种协议}