Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 39 ยท Testing and Hardening

Security Audit Events and Logging

Record who did what: authentication and authorization events, structured audit logs, what never to log, masking secrets and a runnable event-bus stand-in for Spring Security.

Prevention is only half of security. The other half is knowing what happened: who logged in, who was refused, who changed a role. Without an audit trail, an incident turns into guesswork, and attacks such as credential stuffing stay invisible until customers complain.

Spring Security publishes events through Spring's ApplicationEventPublisher. You listen for them and write structured log lines or database rows. The framework cannot run on this site, so the runnable parts are small Java stand-ins for the same pattern (publish an event, many listeners react); the Spring code is shown read-only.

Which events exist

Event Published when
AuthenticationSuccessEvent A credential check succeeded
AbstractAuthenticationFailureEvent (many subclasses) A check failed: AuthenticationFailureBadCredentialsEvent, ...LockedEvent, ...DisabledEvent, ...ExpiredEvent
InteractiveAuthenticationSuccessEvent A form or OAuth2 login completed
AuthorizationDeniedEvent An authorization check refused access
LogoutSuccessEvent A user logged out
SessionFixationProtectionEvent A session id was changed after login

Authorization events are not published by default; you register a publisher bean:

Java
@Bean
AuthorizationEventPublisher authorizationEventPublisher(ApplicationEventPublisher publisher) {
    return new SpringAuthorizationEventPublisher(publisher);
}

Authentication events need AuthenticationEventPublisher, which Spring Boot configures for you (DefaultAuthenticationEventPublisher).

Listening to events

Java
@Component
class SecurityAuditListener {

    private static final Logger audit = LoggerFactory.getLogger("security.audit");

    @EventListener
    void onSuccess(AuthenticationSuccessEvent event) {
        audit.info("event=login_success user={}", event.getAuthentication().getName());
    }

    @EventListener
    void onFailure(AbstractAuthenticationFailureEvent event) {
        audit.warn("event=login_failure user={} reason={}",
            event.getAuthentication().getName(), event.getException().getClass().getSimpleName());
    }

    @EventListener
    void onDenied(AuthorizationDeniedEvent<?> event) {
        audit.warn("event=access_denied user={}", event.getAuthentication().get().getName());
    }
}

Using a dedicated logger name (security.audit) lets you route these lines to their own file, SIEM or retention policy without mixing them into application debug output.

The pattern in miniature

The program below implements an event bus and two listeners: one writes the audit trail, one raises an alert when the same user fails too often. It is the same shape as the Spring code, minus the framework.

Java Publish events, audit and alert (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The sealed interface plus switch makes the compiler check that every event type is handled, a nice property for security code where a forgotten case means a silent gap.

What to log, and what never to log

Log enough to answer "who, what, when, from where, with what result":

  • Timestamp (UTC), event type, outcome (success or failure) and a failure reason category.
  • The username or subject id, the client IP, and a request or correlation id.
  • For privileged actions: the target (which account, which role) and the actor.

Never log:

  • Passwords, even wrong ones: users often mistype a real password into the username field.
  • Tokens: JWTs, refresh tokens, session ids, API keys, CSRF tokens.
  • Full card numbers, national ids and other personal data you do not need.

Also beware of log injection: a username such as bob\nevent=login_success user=admin can forge a second line in a plain-text log. Prefer structured (JSON) logging, or strip control characters from user-supplied values.

Java Neutralize log injection and mask secrets (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The naive line prints a second, forged "login_success" entry for the admin; the safe version keeps everything on one line.

Spring Boot Actuator audit events

If you add spring-boot-starter-actuator and a bean of type AuditEventRepository (the in-memory implementation keeps recent events), Boot translates Spring Security events into AuditEvent objects that you can expose at /actuator/auditevents. That endpoint reveals user names and addresses, so it belongs behind strong authorization. For production, write your own listener that stores events durably, because the in-memory repository is lost at restart.

YAML
management:
  endpoints:
    web:
      exposure:
        include: health,info

From logs to action

Collect the audit lines centrally and alert on patterns, not single lines: many failures for one account, one IP trying many accounts, a successful login right after many failures, access to admin paths by non-admins, role changes outside business hours. The earlier lesson on login throttling covers reacting automatically; audit logs let humans notice what the automation misses.

Retention and privacy rules apply to audit logs too. Decide how long you keep them, who may read them, and how a user's data is handled under regulations such as GDPR.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which event reports that an authorization check refused access?

    AuthorizationDeniedEvent is published when an authorization manager denies access (once an event publisher is configured).
  2. 2. Why use a dedicated logger name such as security.audit?

    Separate routing helps SIEM ingestion, access control and retention.
  3. 3. Which value must never appear in an audit log?

    Secrets in logs become a second place to leak them, and logs are often widely readable.
  4. 4. What is log injection?

    Newlines or control characters in user input can fake entries; clean values or use structured logging.
  5. 5. Which pattern deserves an alert rather than just a log line?

    That sequence often means a guessed password; correlating events is where audit logs pay off.

Summary

  • Spring Security publishes authentication and (with a publisher bean) authorization events; listen to them for an audit trail.
  • Log who, what, when, where and the outcome, with a correlation id; never log passwords or tokens.
  • Prevent log injection with structured logging or by cleaning control characters.
  • Alert on patterns across events, not on single lines.
  • Protect audit endpoints and apply retention and privacy rules.

Next: Production hardening checklist