项目源码地址https://github.com/nieandsun/security
前面文章讲过 SecurityContextPersistenceFilter 请求进来时,会检查session,如果有SecurityContext(可以直接认为已经认证的对象)则拿出来放到线程里即SecurityContextHolder中,返回时校验SecurityContextHolder中是否有securityContext,有则放入session,从而实现认证信息在多个请求中共享。
从这里我们也可以知道在请求中可以从SecurityContextHolder里拿到用户信息。
代码如下:
@GetMapping("/me1")
public Object getCurrentUser1() {
//方式1,直接从SecurityContextHolder中拿到Authentication对象
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return authentication;
}
@GetMapping("/me2")
public Object getCurrentUser2(Authentication authentication) {
//方式2---方式1的简写版
return authentication;
}
@GetMapping("/me3")
public Object getCurrentUser3(@AuthenticationPrincipal UserDetails user) {
//方式3,只获取User对象
return user;
}
其中方式1,2获取的对象信息(Authentication对象)和方式3获取的对象信息如下: