java - 如何在 Spring Boot 的每个请求中获取当前用户?
问题描述
我想在每个请求中获取用户的用户名,以将它们添加到日志文件中。
这是我的解决方案:
LoggedUser
首先,我用一个属性创建了一个static
:
public class LoggedUser {
private static final ThreadLocal<String> userHolder =
new ThreadLocal<>();
public static void logIn(String user) {
userHolder.set(user);
}
public static void logOut() {
userHolder.remove();
}
public static String get() {
return userHolder.get();
}
}
然后我创建了一个支持类来获取用户名:
public interface AuthenticationFacade {
Authentication getAuthentication();
}
@Component
public class AuthenticationFacadeImpl implements AuthenticationFacade {
@Override
public Authentication getAuthentication() {
return SecurityContextHolder.getContext().getAuthentication();
}
}
最后,我在控制器中使用了它们:
@RestController
public class ResourceController {
Logger logger = LoggerFactory.getLogger(ResourceController.class);
@Autowired
private GenericService userService;
@Autowired
private AuthenticationFacade authenticationFacade;
@RequestMapping(value ="/cities")
public List<RandomCity> getCitiesAndLogWhoIsRequesting(){
loggedUser.logIn(authenticationFacade.getAuthentication().getName());
logger.info(LoggedUser.get()); //Log username
return userService.findAllRandomCities();
}
}
问题是我不想AuthenticationFacade
在每一个中都有@Controller
,例如,如果我有 10000 个控制器,那将是很多工作。
你有什么更好的解决方案吗?
解决方案
推荐阅读
- javascript - getCurrentLocation() 在移动浏览器上不起作用(iOS Safari / Brave)
- r - 如何在ggplot中的饼图中添加数字和百分比
- sockets - 使用套接字传递消息是否允许传递大量数据
- java - 当按钮被点击时,while() 停止循环
- python - 使用opencv定义要提取的颜色
- wordpress - Wordpress 联系表格 - 将表格发送到群组电子邮件
- javascript - 在 Jest 中模拟单个依赖函数
- c++ - 如何在 if 语句条件 C++ 中使用字符串变量?
- android - 在 onOptionsItemSelected 中获取特定的 MenuItem 并将其设置为 SHOW_AS_ACTION_NEVER
- hashicorp-vault - 如何在保管库中生成签名 ID 令牌?