【问题标题】:Best way to instrument Spring Boot/Java Config Application检测 Spring Boot/Java 配置应用程序的最佳方法
【发布时间】:2015-07-30 16:01:17
【问题描述】:

我想在 Spring Boot/OAuth2/Java Config 设置中跟踪某些内容并在某处报告这些内容(想想 AWS CloudWatch、Google Analytics 或任何其他类似服务)。 更准确地说,我有一个带有 Spring OAuth2 的授权+资源服务器。

我想跟踪的内容是(但不限于):

  • 登录失败尝试(针对客户端和用户)
  • 登录成功尝试(针对客户端和用户)
  • REST 控制器的使用(如“/say_hello_world”)
  • 异常(身份验证除外)

我计划添加javax.servlet.Filters,但是当使用我的授权服务器(使用@EnableAuthorizationServer 并扩展AuthorizationServerConfigurerAdapter)记录失败的尝试时,它变得很麻烦。我想我需要要么使用我的自定义异常翻译器,要么弄清楚如何在ClientCredentialsTokenEndpointFilter 中设置/包装 AuthenticationManager。

有没有比包装大量的东西来收集我上面提到的信息更好的方法?

更新:

正如我在 cmets 中提到的,我不是在寻找“日志转储”。我需要能够获取例如尝试登录但失败的用户 ID,或使用的无效访问令牌等。

我研究了编写自己的ApplicationListener<ApplicationEvent>、检测AuthenticationFailureBadCredentialsEvent 等并走这条路。 例如,我可以检测到 BadCredentialsException,但随后需要确定它是 InvalidTokenException 还是其他(这是导致 BadCredentialsException 的原因)。 下一个问题是我无法提取已使用但失败的访问令牌。感觉很尴尬,而且比应有的更多黑客攻击。

我不介意经历这样的循环,只是想知道是否有更好的方法。

更新2:

ApplicationListener 是有助于“倾听”Spring 应用程序中正在发生的事情的一件事。 通过提供该接口的实现,可以捕获任何已发布的事件。

  1. InteractiveAuthenticationSuccessEvent 在客户端成功认证时发布(即 clientId 存在且密钥有效)
  2. AuthenticationSuccessEvent 在用户成功认证时发布(即用户名存在且密码匹配)
  3. AuthenticationFailureBadCredentialsEvent 在用户身份验证失败时发布。

#2 和 #3 存在问题,因为在 ProviderManager 中默认设置了 NullEventPublisher,因此我必须更改我的 (Java) 配置以获取这些身份验证事件:

@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
    ... 
    @Autowired
    private AuthenticationEventPublisher authenticationEventPublisher;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
          .authenticationEventPublisher(authenticationEventPublisher)
          ...
    }
    ...
}

现在仍然存在客户端认证失败时接收事件的问题。

InteractiveAuthenticationSuccessEventAbstractAuthenticationProcessingFilterClientCredentialsTokenEndpointFilter 扩展)在成功验证后触发。但是当身份验证失败时,它不会发布任何事件(至少从版本3.0.04.0.1)。

另一种方法是通过设置非NullEventPublisher 来配置AuthenticationManager,但据我所知,如果没有手动设置,就无法在 Spring Boot 中设置ClientCredentialsTokenEndpointFilter宇宙???

【问题讨论】:

  • 使用 log4j 或 slf4j 之类的记录器(我的首选)
  • 我想到了一些更细化和结构化的东西。比如获取用于登录的用户名、用于请求的 HTTP 方法等。

标签: java spring spring-boot spring-security-oauth2 spring-java-config


【解决方案1】:

你可以在春天使用 AOP。创建通知@Before@After@Arround 执行方法,甚至AfterThrowing 以检测发生的任何异常。 使用这种方法,您可以将审核流程与业务逻辑分开。

【讨论】:

  • 确实是将逻辑与其他逻辑分开的好方法。过去,由于代理被其他代理代理等,我遇到了 Spring 爆炸的问题。我想我希望 ApplicationListener 在整个 Spring 项目(尤其是 Spring Security)中始终如一地使用。
猜你喜欢
  • 2011-08-06
  • 2010-09-23
  • 1970-01-01
  • 1970-01-01
  • 2021-09-26
  • 2010-09-10
  • 1970-01-01
  • 2020-02-14
  • 2017-02-24
相关资源
最近更新 更多