|
| 1 | +/* |
| 2 | + * Copyright (c) 2024-25 Smart Sense Consulting Solutions Pvt. Ltd. |
| 3 | + */ |
| 4 | +package ss.mod.demo.web.config.security; |
| 5 | + |
| 6 | +import lombok.extern.slf4j.Slf4j; |
| 7 | +import org.springframework.context.event.EventListener; |
| 8 | +import org.springframework.security.authentication.event.AbstractAuthenticationFailureEvent; |
| 9 | +import org.springframework.security.authorization.AuthorityAuthorizationDecision; |
| 10 | +import org.springframework.security.authorization.AuthorizationDecision; |
| 11 | +import org.springframework.security.authorization.event.AuthorizationDeniedEvent; |
| 12 | +import org.springframework.security.core.GrantedAuthority; |
| 13 | +import org.springframework.stereotype.Component; |
| 14 | + |
| 15 | +import java.util.List; |
| 16 | + |
| 17 | +/** |
| 18 | + * This class is responsible for handling security events such as failed authentication and authorization. |
| 19 | + * It uses Spring's EventListener annotation to listen for specific events and logs relevant information. |
| 20 | + */ |
| 21 | +@Component |
| 22 | +@Slf4j |
| 23 | +public class SecurityEvents { |
| 24 | + |
| 25 | + /** |
| 26 | + * Event listener method to handle failed authentication events. |
| 27 | + * This method logs a message when a failed authentication occurs due to an invalid 'Bearer' token. |
| 28 | + * |
| 29 | + * @param failures It's containing details about the failed authentication. |
| 30 | + */ |
| 31 | + @EventListener |
| 32 | + public void onFailure(AbstractAuthenticationFailureEvent failures) { |
| 33 | + String excMessage = failures.getException().getMessage(); |
| 34 | + log.warn("Failed Authentication --> Invalid 'Bearer' token. {}", excMessage); |
| 35 | + } |
| 36 | + |
| 37 | + /** |
| 38 | + * Event listener method to handle failed authorization events. |
| 39 | + * This method logs a message when a failed authorization occurs due to a missing 'Authorization' header. |
| 40 | + * |
| 41 | + * @param failure It's containing details about the failed authorization. |
| 42 | + */ |
| 43 | + @EventListener |
| 44 | + public void onFailure(AuthorizationDeniedEvent<Object> failure) { |
| 45 | + AuthorizationDecision decision = failure.getAuthorizationDecision(); |
| 46 | + if (decision instanceof AuthorityAuthorizationDecision authorityAuthorizationDecision) { |
| 47 | + List<GrantedAuthority> authorities = authorityAuthorizationDecision.getAuthorities().stream().toList(); |
| 48 | + log.warn("Failed Authorization --> Missing 'Authorization' header OR Required roles are missing in the token. Required roles are {}", authorities); |
| 49 | + } else { |
| 50 | + log.warn("Failed Authorization --> Some issue in authorization."); |
| 51 | + } |
| 52 | + } |
| 53 | +} |
0 commit comments