Security 获取当前会话的三种方法
Posted 流星蝴蝶没有剑
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Security 获取当前会话的三种方法相关的知识,希望对你有一定的参考价值。
Security 获取当前会话的三种方法
- 第一种,通过获取HttpSession的会话中的用户信息,在获取会话对象SecurityContextImpl,然后将用户信息封装。
@GetMapping("getUserSessionH")
@ResponseBody
public String getUerSessionH(HttpSession httpSession) {
Enumeration<String> names = httpSession.getAttributeNames();
String re = "";
while (names.hasMoreElements()) {
String name = names.nextElement();
SecurityContextImpl securityContext = (SecurityContextImpl) httpSession.getAttribute(name);
re += name + "<br>";
re += securityContext + "<br>";
Authentication authentication = securityContext.getAuthentication();
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
re += userDetails + "<br>";
re += userDetails.getUsername() + "<br>" + "<br>";
}
return re;
}
第二种
直接获取上下文
@GetMapping("getUserSessionS")
@ResponseBody
public String getUerSessionS() {
String re = "";
SecurityContext securityContext = SecurityContextHolder.getContext();
re += securityContext + "<br>";
Authentication authentication = securityContext.getAuthentication();
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
re += userDetails + "<br>";
re += userDetails.getUsername() + "<br>" + "<br>";
return re;
}
第三种
直接将用户认证作为参数获取到
@GetMapping("getUserSessionA")
@ResponseBody
public String getUerSessionA(Authentication authentication) {
String re = "";
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
re += userDetails + "<br>";
re += userDetails.getUsername() + "<br>" + "<br>";
return re;
}
以上是关于Security 获取当前会话的三种方法的主要内容,如果未能解决你的问题,请参考以下文章