Spring Security当前用户在线程中 [英] spring security current user in thread
问题描述
我在线程范围内使用spring security时遇到了一些问题
hi i have some problems when use spring security in thread scope
System.out.println(((User) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId());
new Thread(() -> System.out.println(((User) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId())).start();
这两行应该给我当前的用户ID
this two lines should give me current user id
第一行工作正常
第二行给我NullPointerException,因为没有当前用户,它为空值
the second line give me NullPointerException as there is no current user it is null value
我发现此问题是因为我想将许多行保存到歌曲表中,并且拥有@CreatedBy用户,这将要求线程中的当前用户,并且将失败,因为这将为当前用户提供空值
i found this problem as i want to save many rows to the song table and it hava @CreatedBy user and this will ask for current user in thread and will fail as this will give null value for current user
推荐答案
如果您希望生成的线程继承父线程的SecurityContext
,则应设置MODE_INHERITABLETHREADLOCAL
策略.
If you want spawned threads to inherit SecurityContext
of the parent thread, you should set MODE_INHERITABLETHREADLOCAL
strategy.
这篇关于Spring Security当前用户在线程中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!