Just to add a full example of how I managed to do this. Since the existing answer didn't provide a very detailed explanation on how to obtain this goal.
In your spring web security config type following lines.
@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();
}
Then create a custom filter:
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);
}
}
In your properties file (.yml format) add following:
server:
tomcat:
accesslog:
enabled: true
directory: logs
pattern: "%t %a %A %r %s %u %{user}s %B %T %I"
basedir: .
This was everything I had to do to obtain the above result.