1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.openehealth.ipf.boot.atna;
18
19 import org.openehealth.ipf.commons.audit.AuditContext;
20 import org.openehealth.ipf.commons.audit.codes.EventOutcomeIndicator;
21 import org.openehealth.ipf.commons.audit.event.UserAuthenticationBuilder;
22 import org.springframework.boot.actuate.security.AbstractAuthenticationAuditListener;
23 import org.springframework.boot.actuate.security.AuthenticationAuditListener;
24 import org.springframework.security.authentication.event.AbstractAuthenticationEvent;
25 import org.springframework.security.authentication.event.AbstractAuthenticationFailureEvent;
26 import org.springframework.security.core.userdetails.UserDetails;
27 import org.springframework.security.web.authentication.WebAuthenticationDetails;
28
29 import static java.util.Objects.requireNonNull;
30
31
32
33
34 public class AuthenticationListener extends AbstractAuthenticationAuditListener {
35
36 private final AuditContext auditContext;
37 private final AuthenticationAuditListener delegateListener;
38
39 public AuthenticationListener(AuditContext auditContext) {
40 this.auditContext = requireNonNull(auditContext);
41 this.delegateListener = new AuthenticationAuditListener();
42 }
43
44 @Override
45 public void onApplicationEvent(AbstractAuthenticationEvent authenticationEvent) {
46 delegateListener.onApplicationEvent(authenticationEvent);
47
48 EventOutcomeIndicator outcome = authenticationEvent instanceof AbstractAuthenticationFailureEvent ?
49 EventOutcomeIndicator.MajorFailure :
50 EventOutcomeIndicator.Success;
51
52 Object details = authenticationEvent.getAuthentication().getDetails();
53 if (details instanceof WebAuthenticationDetails) {
54 WebAuthenticationDetails webAuthenticationDetails = (WebAuthenticationDetails) details;
55 Object principal = authenticationEvent.getAuthentication().getPrincipal();
56 if (principal instanceof UserDetails) {
57 UserDetails userDetails = (UserDetails) principal;
58
59 UserAuthenticationBuilder builder = new UserAuthenticationBuilder.Login(outcome)
60 .setAuditSource(auditContext);
61 if (userDetails.getUsername() != null) {
62 builder.setAuthenticatedParticipant(
63 userDetails.getUsername(),
64 webAuthenticationDetails.getRemoteAddress());
65 };
66 if (webAuthenticationDetails.getRemoteAddress() != null) {
67 builder.setAuthenticatingSystemParticipant(
68 auditContext.getSendingApplication(),
69 webAuthenticationDetails.getRemoteAddress());
70 }
71 auditContext.audit(builder.getMessage());
72 }
73 }
74 }
75 }