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

前端代码:

效果:

相关推荐
独泪了无痕8 小时前
探索Pinyin4j-Java中的拼音转换利器
java·后端
道尔柯南9 小时前
C++ string 类详解:从常用接口到深拷贝,彻底掌握字符串处理
android·java·c++
kingx310 小时前
Bugku 3122 谷歌小恐龙题解:纯离线逆向 Vault 的 AES-GCM 加密资源(附 Python 解密器)
java·逆向·ctf·bugku·aes-gcm
翔云12345612 小时前
RocksDB中,客户端每写入一次数据,需要访问几次磁盘
运维·数据库·mysql
DevOpenClub12 小时前
职教高考控制线 API:招生类别枚举、筛选与空分数含义
java·数据库·高考
露天赏雪13 小时前
第3篇:Sentinel熔断降级实战:大模型接口抖动时的服务兜底方案
java·开发语言·人工智能·spring boot·spring·servlet·sentinel
天天被压力13 小时前
【A股分钟级高频数据完全手册 #06】北交所分钟级数据接口:京市股票Pro版最新分时
java·人工智能·python
天天被压力13 小时前
【A股分钟级高频数据完全手册 #05】指数历史分钟数据接口:Pro版沪深指数分时回放
java·人工智能·python
captain37614 小时前
▲统一功能——DispatcherServlet源码分析
java·spring·java-ee·log4j·maven
金銀銅鐵14 小时前
JDK 21 中 List.of 的实现细节:从 List12 到 ListN
java·后端·ai编程