5

I run a sample Spring Security (hello world) web application in Apache Tomcat 8. What I'm trying to see is the user information in Tomcat Access Logs, but it looks that this information is not there. Example for access log entries:

0:0:0:0:0:0:0:1 - - [06/Nov/2019:09:41:57 +0200] "GET / HTTP/1.1" 200 422
0:0:0:0:0:0:0:1 - - [06/Nov/2019:09:41:59 +0200] "GET /hello HTTP/1.1" 200 83

The access log configuration in the Tomcat server.xml is:

<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
           prefix="localhost_access_log" suffix=".txt"
           pattern="common" />

pattern="common" corresponds to the Common Log Format defined by '%h %l %u %t "%r" %s %b' as it is described here. Tomcat documentation also states:

%u - Remote user that was authenticated (if any), else '-'

Is there any additional configuration that I should apply to make the user visible in the access logs?

Ori Marko
  • 56,308
  • 23
  • 131
  • 233
Stiliyan Vasilev
  • 179
  • 2
  • 3
  • 14

1 Answers1

5

As answered, it may not work as expected

Tomcat's access log valve, this won't work, since Tomcat is unaware of Spring Security, which operates entirely within your application.

You may use a filter:

The easiest option would be to just add your own filter (e.g. in web.xml) after Spring Security, and dump the information you want

Other solution suggested in Config9, you may need to include the username as session attribute

Possibly this is not sufficient as common pattern already contains %u parameter. In this case I would recommend two additional steps:

1) Put user’s name into request session parameter, something like:

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

2) Add following parameter in access log pattern: %{username}s

server.tomcat.accesslog.pattern=%h %l %t %u %{username}s "%r" %s %b
Ori Marko
  • 56,308
  • 23
  • 131
  • 233
  • Do you have some example how this filter should looks like in order to display to user? – Stiliyan Vasilev Nov 06 '19 at 08:27
  • @StiliyanVasilev see https://code-held.com/2019/05/09/custom-authentication-with-spring-security/ – Ori Marko Nov 06 '19 at 08:33
  • I have implement custom filter and try to print it in access logs via %{username}s and it work correctly. I also try to print logs with LogbackValve via %reqAttribute{username}, but it return “-“. Do you know how could I get username in LogbackValve scenario? – Stiliyan Vasilev Nov 06 '19 at 13:47
  • @StiliyanVasilev I currently don't know – Ori Marko Nov 06 '19 at 13:53
  • @StiliyanVasilev I think you can ask a new specific question about logging using LogbackValve with session attribute – Ori Marko Nov 07 '19 at 11:04