繁体   English   中英

Spring 使用嵌入式 tomcat 引导 + 带有身份验证用户的访问日志

[英]Spring boot with embedded tomcat + access log with authentication user

我正在使用带有嵌入式 tomcat + spring 安全性的 spring 引导。 我来自 tomcat 的访问日志看起来像这样

IP - - [14/Feb/2017:08:49:50 +0200] “GET /page/2 HTTP/1.1”200 2606

那么,我怎样才能使日志文件看起来像

IP - - [14/Feb/2017:08:49:50 +0200]用户名- "GET /page/2 HTTP/1.1" 200 2606

每个请求都必须具有从中发出的用户名。 对于安全身份验证,我使用带有数据库用户名和密码信息的 spring 安全性。

您可能需要将应用程序属性中的访问日志模式更改为如下所示:

server.tomcat.accesslog.pattern=%h %l %t %u "%r" %s %b

其中%u已通过身份验证的远程用户(请参阅此处的示例)。


UPD :这可能还不够,因为普通模式已经包含%u参数。 在这种情况下,我会推荐两个额外的步骤:

  1. 将用户名放入请求会话参数中,例如:

request.getSession().setAttribute("username", user.getName());

  1. 在访问日志模式中添加以下参数: %{username}s

    server.tomcat.accesslog.pattern=%h %l %t %u %{username}s "%r" %s %b

应采取指定属性username来自HttpSession ,因为它描述了这里

只是为了添加一个完整的例子来说明我是如何做到这一点的。 由于现有答案没有提供有关如何实现此目标的非常详细的解释。

在您的 spring web 安全配置中键入以下行。

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    return http
            .csrf().disable()
            .authorizeRequests()
            .anyRequest().authenticated()
            .and()
            .httpBasic()
            .and()
            .addFilterAfter(usernameAccessLogFilter(), BasicAuthenticationFilter.class)
            .build();
}

@Bean
    public UsernameAccessLogFilter usernameAccessLogFilter(){
        return new UsernameAccessLogFilter();
    }

然后创建一个自定义过滤器:

public class UsernameAccessLogFilter extends GenericFilterBean {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    HttpServletRequest request = ((HttpServletRequest) servletRequest);

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if(authentication != null) {
        request.getSession().setAttribute("user", authentication.getName());
    }
    filterChain.doFilter(servletRequest, servletResponse);
}

}

在您的属性文件(.yml 格式)中添加以下内容:

server:
  tomcat:
    accesslog:
      enabled: true
      directory: logs
      pattern: "%t %a %A %r %s %u %{user}s %B %T %I"
    basedir: .

这是我为获得上述结果所要做的一切。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM