SecurityContextHolder 按字面意思理解,就是安全上下文支持,它是一个工具类,目的是用来保存应用程序中当前使用人的安全上下文。在使用了 Spring Security 的 Spring Boot 应用中,我们在后端线程中想要获取登录用户的信息,可以使用代码:
SecurityContextHolder.getContext().getAuthentication().getPrincipal()
例如在下面的接口中,使用了异步调用其它组件服务的feign接口,此时需要为feign传递认证信息token,需要做如下处理:
@PostMapping(value = "/task/start", produces = MediaType.APPLICATION_JSON_VALUE)
public void asyncStartImportTask(@RequestBody @Valid TaskRequest request) {
SecurityContext context = SecurityContextHolder.getContext();
executor.submit(() -> {
try {
SecurityContextHolder.setContext(context);
//......................
SecurityContext context = SecurityContextHolder.getContext();
OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) context.getAuthentication().getDetails();
String token = details.getTokenValue();
FeignClientInterceptor.setToken(token);
// 使用feign调用其它组建的接口,需要携带认证的token信息
List<ResourceEntity> result = testApi.getAllResources();
//.........................
} finally {
SecurityContextHolder.clearContext();
}
});
}