webapi 能用session保存用户的信息吗

webapi 能用session保存用户的信息吗

问题描述:

各位大哥大佬好,小弟不才有个问题想要请问下各位:
需求:
webapi 在请求的时候带了token ,可以在Authorfilter拦截中通过数据库查找出对应的用户,但是我不想再次在控制内再次查找该用户,所以我将这个用户的相关信息保存到请求的头内。
然后今天我想能不能把相关的用户数据保存到session内,这样做会有问题吗,或则说可行吗
图片说明

基于token的一般都不用session吧?你在filter里拦截了以后,把用户信息放在在SecurityContextHolder里了,你在controller直接取就行。
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authentication);

controller:
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Object principal = authentication.getPrincipal();
if (principal instanceof UserDetails) {
String username = ((UserDetails)principal).getUsername();
} else {
String username = principal.toString();
}

我用过基于shiro认证框架的,用户基本信息可通ehcache或者是redis来缓存当前用户登录信息,而最为基础的你可以参考session怎么缓存用户信息这个问题