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");
    }
}

前端代码:

效果:

相关推荐
Knight_AL2 小时前
MySQL STORED 生成列(Generated Column)详解:让 SQL 变快的秘密武器
数据库·sql·mysql
请为小H留灯2 小时前
Java实际开发@常用注解(附实战场景)
java·后端·个人开发
老华带你飞3 小时前
在线教育|基于springboot + vue在线教育系统(源码+数据库+文档)
java·开发语言·数据库·vue.js·spring boot·后端
路边草随风3 小时前
java操作cosn使用
java·大数据·hadoop
TT哇3 小时前
【项目】玄策五子——匹配模块
java·spring boot·websocket·spring·java-ee·maven
认真敲代码的小火龙3 小时前
【JAVA项目】基于JAVA的医院管理系统
java·开发语言·课程设计
Predestination王瀞潞3 小时前
Java EE开发技术 (报错解决 兼容问题 及 Jakara EE Web 官方手册提供的API接口聚合包)
java·java-ee·jstl·jakara背景
断剑zou天涯3 小时前
【算法笔记】Manacher算法
java·笔记·算法
光羽隹衡3 小时前
MySQL的安装
数据库·mysql
脸大是真的好~3 小时前
尚硅谷-mysql专项训练-数据库服务的优化-慢查询-EXPLAIN字段
数据库·mysql·性能优化