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

前端代码:

效果:

相关推荐
程序员夏末3 分钟前
【MySQL | 第一篇】 深入理解三大日志(undo Redo Bin)
数据库·mysql
jgbazsh21 分钟前
Redis6.2.6下载和安装
java
于先生吖25 分钟前
JAVA 本地生活服务项目实战 家政 5.0 系统前后端分离部署
java·开发语言·生活
左左右右左右摇晃32 分钟前
Java并发——锁的状态演变
java·开发语言·笔记
Roselind_Yi34 分钟前
排查Visual C++堆损坏(HEAP CORRUPTION)错误:从报错到解决的完整复盘
java·开发语言·c++·spring·bug·学习方法·远程工作
bing_15839 分钟前
spring Boot 3.0 和2.0的区别
java·spring boot·后端
Thomas.Sir40 分钟前
Shiro认证与授权:Java安全框架的核心机制
java·安全·shiro·权限控制
wuqingshun3141591 小时前
谈一下Daemon线程
java·开发语言
ruxingli1 小时前
MySQL优化
数据库·mysql
启山智软1 小时前
【对比了几家电商商城系统】
java·开源