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

前端代码:

效果:

相关推荐
边境悍匪2 分钟前
蜗牛学苑 Java 智能体学习 Day44|Vue 前端项目搭建 思维导图复盘
java·开发语言·spring boot·学习·阿里云
万年咸鱼7 分钟前
public class 和 class 的区别详解
java
焦虑的说说7 分钟前
redis知识汇总
java·redis
Wang's Blog12 分钟前
Java 接入Redis: 密码认证与远程连接配置
java·服务器·redis
SunnyDays101127 分钟前
Java 拆分 Word 文档教程:按页、分页符和分节符拆分
java·word·分页·拆分
彧azz28 分钟前
Java学习记录:判断语句
java·笔记·学习·算法
企业数字化笔记32 分钟前
一批相同的电脑怎么建账?数量管理、单件编码和拆分规则
java·后端·电脑
君顾142 分钟前
本地城市社区家政物业联动系统源码:架构设计与派单联动实战
java·开发语言·健身房
hai_android44 分钟前
Android 组件化开发实践
android·java·kotlin