Skip to content

Instantly share code, notes, and snippets.

@arleighdickerson
Created July 13, 2025 17:16
Show Gist options
  • Save arleighdickerson/ed9906083fd08e8bb4ca5bcb911f5f81 to your computer and use it in GitHub Desktop.
Save arleighdickerson/ed9906083fd08e8bb4ca5bcb911f5f81 to your computer and use it in GitHub Desktop.
import io.arleigh.gantry.util.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.slf4j.MDC;
import org.springframework.boot.actuate.audit.listener.AuditApplicationEvent;
import org.springframework.context.event.EventListener;
import org.springframework.security.access.event.AbstractAuthorizationEvent;
import org.springframework.security.access.event.AuthorizationFailureEvent;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;
import java.util.Map;
import java.util.Optional;
@Component
@Slf4j(topic = "AuditLogger")
class LoggingAuditEventListener {
@EventListener
public void on(AuditApplicationEvent event) {
Map<String, String> backup = MDC.getCopyOfContextMap();
MDC.put("event.type", event.getAuditEvent().getType());
MDC.put("event.principal", Optional.ofNullable(event.getAuditEvent()
.getPrincipal()).orElse("(missing)")
);
log.debug("An AuditEvent was received: {}", event);
if (backup != null) {
MDC.setContextMap(backup);
}
}
@EventListener
public void on(AbstractAuthorizationEvent abstractEvent) {
Map<String, String> backup = MDC.getCopyOfContextMap();
if (abstractEvent instanceof AuthorizationFailureEvent) {
AuthorizationFailureEvent event = (AuthorizationFailureEvent) abstractEvent;
MDC.put("event.type", "AUTHORIZATION_FAILURE_EVENT");
MDC.put("event.principal", Optional.ofNullable(event.getAuthentication())
.map(SecurityUtils::getPrincipalName).orElse("(missing)")
);
val source = event.getSource();
val method = ReflectionUtils.findMethod(source.getClass(), "getRequestUrl");
if (method != null) {
method.setAccessible(true);
try {
String requestUrl = (String) ReflectionUtils.invokeMethod(method, source);
MDC.put("source.requestUrl", requestUrl);
} catch (Throwable t) {
log.error("could not reflect source.requestUrl", t);
}
}
log.debug("An AuthorizationFailureEvent was received: {}", abstractEvent);
}
if (backup != null) {
MDC.setContextMap(backup);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment