下面列出了org.springframework.security.authentication.event.InteractiveAuthenticationSuccessEvent#org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void onApplicationEvent(AbstractAuthenticationEvent appEvent) {
String currentUserName = extractUserName(appEvent);
if (currentUserName == null || isLockMechanismDisabled()) {
return;
}
if (appEvent instanceof AuthenticationSuccessEvent &&
accessCounter.containsKey(currentUserName) &&
accessCounter.get(currentUserName) < maxLoginFailures) {
accessCounter.remove(currentUserName);
lastFailedLogin.remove(currentUserName);
}
if (appEvent instanceof AuthenticationFailureBadCredentialsEvent) {
if (accessCounter.containsKey(currentUserName)) {
accessCounter.put(currentUserName, accessCounter.get(currentUserName) + 1);
} else {
accessCounter.put(currentUserName, 1);
}
lastFailedLogin.put(currentUserName, new Date());
}
}
@Override
public void onApplicationEvent(AbstractAuthenticationEvent event) {
try {
if (event instanceof AuthenticationSuccessEvent) {
process((AuthenticationSuccessEvent) event);
} else if (event instanceof AuthenticationFailureBadCredentialsEvent) {
process((AuthenticationFailureBadCredentialsEvent) event);
} else if (event instanceof AuthenticationFailureDisabledEvent) {
process((AuthenticationFailureDisabledEvent) event);
}
// igonre all other events
} catch (Exception e) {
logger.error("Exception in Spring Event Listener.", e);
}
}
protected void process(
AuthenticationFailureBadCredentialsEvent authFailEvent) {
Authentication auth = authFailEvent.getAuthentication();
WebAuthenticationDetails details = (WebAuthenticationDetails) auth
.getDetails();
String remoteAddress = details != null ? details.getRemoteAddress()
: "";
String sessionId = details != null ? details.getSessionId() : "";
logger.info("Login Unsuccessful:" + auth.getName() + " | Ip Address:"
+ remoteAddress + " | Bad Credentials");
sessionMgr.processFailureLogin(
XXAuthSession.AUTH_STATUS_WRONG_PASSWORD,
XXAuthSession.AUTH_TYPE_PASSWORD, auth.getName(),
remoteAddress, sessionId);
}
@Override
public void onApplicationEvent(AuthenticationFailureBadCredentialsEvent authenticationFailureBadCredentialsEvent) {
//只有账号密码登录才回更新登录失败次数
if (authenticationFailureBadCredentialsEvent.getAuthentication().getClass().equals(UsernamePasswordAuthenticationToken.class)) {
userService.processLoginFail(authenticationFailureBadCredentialsEvent.getAuthentication().getName());
log.info("Authentication failure: " + authenticationFailureBadCredentialsEvent.getAuthentication().getName());
}
}
private SubsonicRESTController.ErrorCode authenticate(HttpServletRequest httpRequest, String username, String password, String salt, String token, Authentication previousAuth) {
// Previously authenticated and username not overridden?
if (username == null && previousAuth != null) {
return null;
}
if (salt != null && token != null) {
User user = securityService.getUserByName(username);
if (user == null) {
return SubsonicRESTController.ErrorCode.NOT_AUTHENTICATED;
}
String expectedToken = DigestUtils.md5Hex(user.getPassword() + salt);
if (!expectedToken.equals(token)) {
return SubsonicRESTController.ErrorCode.NOT_AUTHENTICATED;
}
password = user.getPassword();
}
if (password != null) {
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
authRequest.setDetails(authenticationDetailsSource.buildDetails(httpRequest));
try {
Authentication authResult = authenticationManager.authenticate(authRequest);
SecurityContextHolder.getContext().setAuthentication(authResult);
return null;
} catch (AuthenticationException x) {
eventPublisher.publishEvent(new AuthenticationFailureBadCredentialsEvent(authRequest, x));
return SubsonicRESTController.ErrorCode.NOT_AUTHENTICATED;
}
}
return SubsonicRESTController.ErrorCode.MISSING_PARAMETER;
}
@Override
public void onApplicationEvent(final AuthenticationFailureBadCredentialsEvent e) {
final WebAuthenticationDetails auth = (WebAuthenticationDetails) e.getAuthentication().getDetails();
if (auth != null) {
loginAttemptService.loginFailed(auth.getRemoteAddress());
}
}
@Override
public void onApplicationEvent(AbstractAuthenticationEvent event) {
if (event instanceof AuthenticationSuccessEvent) {
log.debug("Authentication OK: {}", event.getAuthentication().getName());
// Activity log
Object details = event.getAuthentication().getDetails();
String params = null;
if (details instanceof WebAuthenticationDetails) {
WebAuthenticationDetails wad = (WebAuthenticationDetails) details;
params = wad.getRemoteAddress();
} else if (GenericHolder.get() != null) {
params = (String) GenericHolder.get();
}
// AUTOMATION - POST
Map<String, Object> env = new HashMap<>();
env.put(AutomationUtils.USER, event.getAuthentication().getName());
try {
AutomationManager.getInstance().fireEvent(AutomationRule.EVENT_USER_LOGIN, AutomationRule.AT_POST, env);
} catch (Exception e) {
log.info("Automation ERROR: {}", e.getCause());
}
UserActivity.log(event.getAuthentication().getName(), "LOGIN", null, null, params);
} else if (event instanceof AuthenticationFailureBadCredentialsEvent) {
log.info("Authentication ERROR: {}", event.getAuthentication().getName());
}
}
@EventListener
public void onBadCredentials(AuthenticationFailureBadCredentialsEvent event){
String userName = event.getAuthentication().getName();
AtomicInteger errorTimes = getExceptionTimesByUser(userName);
int times = errorTimes.incrementAndGet();
if(log.isWarnEnabled()){
log.warn("The user[{}] has logged in {} times failed", userName, times);
}
}
@Override
public void onApplicationEvent(AuthenticationFailureBadCredentialsEvent event) {
this.transactionTemplate.execute(ts -> {
updateLockedProperties(event);
return null;
});
}
public void onApplicationEvent(ApplicationEvent event) {
try {
if (event instanceof InteractiveAuthenticationSuccessEvent) {
this.logLoginSuccess(event);
}
if (event instanceof AuthenticationFailureBadCredentialsEvent) {
this.logBadCredential(event);
}
if (event instanceof AuthenticationFailureLockedEvent) {
this.logLocked(event);
}
if (event instanceof AuthenticationFailureDisabledEvent) {
this.logDisabled(event);
}
if (event instanceof AuthenticationFailureExpiredEvent) {
this.logAccountExpired(event);
}
if (event instanceof AuthenticationFailureCredentialsExpiredEvent) {
this.logCredentialExpired(event);
}
} catch (Exception ex) {
logger.error(ex.getMessage(), ex);
}
}
public void logBadCredential(ApplicationEvent event) throws Exception {
AuthenticationFailureBadCredentialsEvent authenticationFailureBadCredentialsEvent = (AuthenticationFailureBadCredentialsEvent) event;
Authentication authentication = authenticationFailureBadCredentialsEvent
.getAuthentication();
logger.info("logBadCredential : {}", authentication);
String tenantId = this.getTenantId(authentication);
Object principal = authentication.getPrincipal();
String userId = null;
if (principal instanceof SpringSecurityUserAuth) {
userId = ((SpringSecurityUserAuth) principal).getId();
} else {
userId = authentication.getName();
}
AuditDTO auditDto = new AuditDTO();
auditDto.setUserId(userId);
auditDto.setAuditTime(new Date());
auditDto.setAction("login");
auditDto.setResult("failure");
auditDto.setApplication("lemon");
auditDto.setClient(getUserIp(authentication));
auditDto.setServer(InetAddress.getLocalHost().getHostAddress());
auditDto.setDescription(authenticationFailureBadCredentialsEvent
.getException().getMessage());
auditDto.setTenantId(tenantId);
auditConnector.log(auditDto);
ctx.publishEvent(new LoginEvent(authentication, userId, this
.getSessionId(authentication), "badCredentials", "default",
tenantId));
}
@ExtDirectMethod(ExtDirectMethodType.FORM_POST)
@PreAuthorize("hasAuthority('PRE_AUTH')")
@Transactional
public ExtDirectFormPostResult signin2fa(HttpServletRequest request,
@AuthenticationPrincipal JpaUserDetails jpaUserDetails,
@RequestParam("code") int code) {
User user = jpaUserDetails.getUser(this.jpaQueryFactory);
if (user != null) {
if (TotpAuthUtil.verifyCode(user.getSecret(), code, 3)) {
user.setLastAccess(ZonedDateTime.now(ZoneOffset.UTC));
jpaUserDetails.grantAuthorities();
Authentication newAuth = new UsernamePasswordAuthenticationToken(
jpaUserDetails, null, jpaUserDetails.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(newAuth);
ExtDirectFormPostResult result = new ExtDirectFormPostResult();
result.addResultProperty(AUTH_USER, new UserDetailDto(jpaUserDetails,
user, CsrfController.getCsrfToken(request)));
return result;
}
BadCredentialsException excp = new BadCredentialsException(
"Bad verification code");
AuthenticationFailureBadCredentialsEvent event = new AuthenticationFailureBadCredentialsEvent(
SecurityContextHolder.getContext().getAuthentication(), excp);
this.applicationEventPublisher.publishEvent(event);
user = jpaUserDetails.getUser(this.jpaQueryFactory);
if (user.getLockedOutUntil() != null) {
HttpSession session = request.getSession(false);
if (session != null) {
Application.logger.debug("Invalidating session: " + session.getId());
session.invalidate();
}
SecurityContext context = SecurityContextHolder.getContext();
context.setAuthentication(null);
SecurityContextHolder.clearContext();
}
}
return new ExtDirectFormPostResult(false);
}
private void updateLockedProperties(AuthenticationFailureBadCredentialsEvent event) {
Object principal = event.getAuthentication().getPrincipal();
if (this.loginLockAttempts != null
&& (principal instanceof String || principal instanceof JpaUserDetails)) {
User user = null;
if (principal instanceof String) {
user = this.jpaQueryFactory.selectFrom(QUser.user)
.where(QUser.user.loginName.eq((String) principal))
.where(QUser.user.deleted.isFalse()).fetchFirst();
}
else {
user = ((JpaUserDetails) principal).getUser(this.jpaQueryFactory);
}
if (user != null) {
if (user.getFailedLogins() == null) {
user.setFailedLogins(1);
}
else {
user.setFailedLogins(user.getFailedLogins() + 1);
}
if (user.getFailedLogins() >= this.loginLockAttempts) {
if (this.loginLockMinutes != null) {
user.setLockedOutUntil(ZonedDateTime.now(ZoneOffset.UTC)
.plusMinutes(this.loginLockMinutes));
}
else {
user.setLockedOutUntil(
ZonedDateTime.now(ZoneOffset.UTC).plusYears(1000));
}
}
this.jpaQueryFactory.getEntityManager().merge(user);
}
else {
Application.logger.warn("Unknown user login attempt: {}", principal);
}
}
else {
Application.logger.warn("Invalid login attempt: {}", principal);
}
}
@Override
public void onApplicationEvent(AuthenticationFailureBadCredentialsEvent event) {
Object username = event.getAuthentication().getPrincipal();
LOG.info("Failed login using username='{}'", username);
}