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 小时前
set和map
java·学习
ha_lydms2 小时前
5、Spark函数_s/t
java·大数据·python·spark·数据处理·maxcompute·spark 函数
黄河滴滴3 小时前
java系统变卡变慢的原因是什么?从oom的角度分析
java·开发语言
侠客行03173 小时前
Mybatis二级缓存实现详解
java·mybatis·源码阅读
老华带你飞3 小时前
农产品销售管理|基于java + vue农产品销售管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot·后端
Edward111111114 小时前
tomcat_servlet
java·servlet·tomcat
短剑重铸之日4 小时前
SpringBoot声明式事务的源码解析
java·后端·spring·springboot
李白的粉4 小时前
基于springboot的银行客户管理系统(全套)
java·spring boot·毕业设计·课程设计·源代码·银行客户管理系统
JIngJaneIL4 小时前
基于springboot + vue房屋租赁管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot·后端
努力的小南5 小时前
Java字节码文件常量池索引两个问题
java·常量池·字节码文件·黑马jvm字节码文件常量池索引