SpringSecurity下代码中手动指定用户登录

2022-08-22 666点热度 0人点赞 0条评论

需求说明

在用SpringSecurity做登录权限控制的时候,例如后台做代用户登录功能的时候,需要以指定某个用户登录账号。这里是以session作为登录状态管控的。

实现

// 根据自己的业务获得登录用户的账号
Account account = systemDao.getAccountByNo(loginNo);
// 组装出token
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
account, null, account.getAuthorities());
token.setDetails(new WebAuthenticationDetails(request));
SecurityContextHolder.getContext().setAuthentication(token);
HttpSession session = request.getSession(true);
session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
SecurityContextHolder.getContext());
// 其他业务需求在session中存入相关的值
// session.setAttribute...
// 根据自己的业务获得登录用户的账号 Account account = systemDao.getAccountByNo(loginNo); // 组装出token UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( account, null, account.getAuthorities()); token.setDetails(new WebAuthenticationDetails(request)); SecurityContextHolder.getContext().setAuthentication(token); HttpSession session = request.getSession(true); session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext()); // 其他业务需求在session中存入相关的值 // session.setAttribute...
// 根据自己的业务获得登录用户的账号
Account account = systemDao.getAccountByNo(loginNo);

// 组装出token
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
        account, null, account.getAuthorities());

token.setDetails(new WebAuthenticationDetails(request));
SecurityContextHolder.getContext().setAuthentication(token);
HttpSession session = request.getSession(true);
session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
        SecurityContextHolder.getContext());

// 其他业务需求在session中存入相关的值
// session.setAttribute...

 

 

admin

这个人很懒,什么都没留下

文章评论

您需要 登录 之后才可以评论