Spring Security 实现后台切换用户

Spring Security version

后端代码:

java 复制代码
/**
 * @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");
    }
}

前端代码:

效果:

相关推荐
皮皮林55114 小时前
SpringBoot 全局/局部双模式 Gzip 压缩实战:14MB GeoJSON 秒变 3MB
java·spring boot
jakeswang14 小时前
全解MySQL之死锁问题分析、事务隔离与锁机制的底层原理剖析
数据库·mysql
weixin_4569042715 小时前
Spring Boot 用户管理系统
java·spring boot·后端
趁你还年轻_15 小时前
异步编程CompletionService
java
DKPT15 小时前
Java内存区域与内存溢出
java·开发语言·jvm·笔记·学习
sibylyue15 小时前
Guava中常用的工具类
java·guava
奔跑吧邓邓子15 小时前
【Java实战㉞】从0到1:Spring Boot Web开发与接口设计实战
java·spring boot·实战·web开发·接口设计
一成码农15 小时前
MySQL问题7
数据库·mysql
专注API从业者15 小时前
Python/Java 代码示例:手把手教程调用 1688 API 获取商品详情实时数据
java·linux·数据库·python
奔跑吧邓邓子15 小时前
【Java实战㉝】Spring Boot实战:从入门到自动配置的进阶之路
java·spring boot·实战·自动配置