java - 从其他类访问经过身份验证的用户(没有 SecurityContextHolder)
问题描述
我想在我的微服务中实现 mongodb 审计,但我不知道如何处理来自 AuditorAware 类的经过身份验证的用户。在单一应用程序中,我们可以使用SecurityContextHolder处理用户。但就我而言,SecurityContextHolder仅在 zuul 微服务(我管理安全性的地方)中可用。所以我不能使用这个AuditorAware类的例子。
class SpringSecurityAuditAwareImpl implements AuditorAware<Long> {
@Override
public Optional<Long> getCurrentAuditor() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null ||
!authentication.isAuthenticated() ||
authentication instanceof AnonymousAuthenticationToken) {
return Optional.empty();
}
UserPrincipal userPrincipal = (UserPrincipal) authentication.getPrincipal();
return Optional.ofNullable(userPrincipal.getId());
}
为了向我的微服务的控制器传递身份验证,我创建了这个类,它在每个请求中提取令牌,构造经过身份验证的用户对象,并将其注入到控制器方法的参数中
class AuthenticationHandler : HandlerMethodArgumentResolver
{
@Autowired
private lateinit var tokenUtils : TokenUtils
override fun supportsParameter(parameter : MethodParameter) : Boolean
{
return parameter.hasParameterAnnotation(Authentication::class.java)
&& parameter.parameterType == AuthUser::class.java
&& (parameter.getParameterAnnotation(Authentication::class.java)?.required == true)
}
override fun resolveArgument(parameter : MethodParameter,mavContainer : ModelAndViewContainer?, webRequest : NativeWebRequest,binderFactory : WebDataBinderFactory?) : AuthUser
{
return try
{
val token : String? = tokenUtils.getTokenHeader(webRequest)
tokenUtils.getUser(token!!)!!
}
catch (exception : Exception)
{
throw UnauthorizedException()
}
}
}
有没有一种干净的方法可以用来从 AuditorAware 类传递在 AuthenticationHandler 类中创建的 AuthUser 对象?
解决方案
推荐阅读
- php - 如何通过 PHP 代码将文本和图像内容插入谷歌文档
- c - 让用户在 C 中指定一个文件名
- python - 无法在 Tensorflow 的 Keras 中添加两层
- javascript - EventListeners 不适用于 A-Frame 父实体
- docker - 将 JIRA 从本机实例恢复到 docker 容器
- kdb - 如何在kdb中计算年初至今的小计
- javascript - 使用锚标签下载文件时如何获取下载时间?
- c# - 哪个是 ASP.NET Core 上 CloudTableClient 类的最佳 DI 注册范围
- ios - 如何编辑 UIScrollView 大小?
- mongodb - 将具有访问控制的 GKE mongo 公开到 Internet