AuthenticationFailureBadCredentialsListener.java
/*
* Copyright 2023 Global Crop Diversity Trust
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.genesys.blocks.security.lockout;
import org.genesys.blocks.security.model.BasicUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;
/**
* Log failed login attempt and notify {@link AccountLockoutManager}.
*
* @author Matija Obreza, matija.obreza@croptrust.org
*/
@Component
@Slf4j
public class AuthenticationFailureBadCredentialsListener implements ApplicationListener<AuthenticationFailureBadCredentialsEvent> {
/** The lockout manager. */
@Autowired
private AccountLockoutManager lockoutManager;
/*
* (non-Javadoc)
* @see org.springframework.context.ApplicationListener#onApplicationEvent(org.
* springframework.context.ApplicationEvent)
*/
@Override
public void onApplicationEvent(final AuthenticationFailureBadCredentialsEvent event) {
final Object principal = event.getAuthentication().getPrincipal();
String userName = null;
if (principal instanceof String) {
userName = (String) principal;
} else if (principal instanceof BasicUser<?>) {
userName = ((BasicUser<?>) principal).getUsername();
} else if (principal instanceof UserDetails) {
userName = ((UserDetails) principal).getUsername();
}
final Object details = event.getAuthentication().getDetails();
if (details instanceof WebAuthenticationDetails) {
final WebAuthenticationDetails wad = (WebAuthenticationDetails) details;
// This can be picked up by fail2ban http://www.fail2ban.org/
log.warn("Failed login attempt for username={} from IP={}", userName, wad.getRemoteAddress());
}
lockoutManager.handleFailedLogin(userName);
}
}