首页 > 解决方案 > 从其他类访问经过身份验证的用户(没有 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 对象?

标签: javaspringspring-data

解决方案


推荐阅读