org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent Java Examples

The following examples show how to use org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: InternalAuthenticationProvider.java    From osiam with MIT License 7 votes vote down vote up
@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());
    }
}
 
Example #2
Source File: SpringEventListener.java    From ranger with Apache License 2.0 6 votes vote down vote up
@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);
}
   }
 
Example #3
Source File: SpringEventListener.java    From ranger with Apache License 2.0 6 votes vote down vote up
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);
   }
 
Example #4
Source File: AuthenticationFailureEventListener.java    From cola with MIT License 5 votes vote down vote up
@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());
	}
}
 
Example #5
Source File: RESTRequestParameterProcessingFilter.java    From airsonic with GNU General Public License v3.0 5 votes vote down vote up
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;
    }
 
Example #6
Source File: AuthenticationFailureListener.java    From spring-boot with Apache License 2.0 5 votes vote down vote up
@Override
public void onApplicationEvent(final AuthenticationFailureBadCredentialsEvent e) {
    final WebAuthenticationDetails auth = (WebAuthenticationDetails) e.getAuthentication().getDetails();
    if (auth != null) {
        loginAttemptService.loginFailed(auth.getRemoteAddress());
    }
}
 
Example #7
Source File: LoggerListener.java    From document-management-system with GNU General Public License v2.0 5 votes vote down vote up
@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());
	}
}
 
Example #8
Source File: ExceptionUserChecker.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@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);
	}
}
 
Example #9
Source File: UserAuthErrorHandler.java    From eds-starter6-jpa with Apache License 2.0 5 votes vote down vote up
@Override
public void onApplicationEvent(AuthenticationFailureBadCredentialsEvent event) {
	this.transactionTemplate.execute(ts -> {
		updateLockedProperties(event);
		return null;
	});
}
 
Example #10
Source File: SpringSecurityListener.java    From lemon with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example #11
Source File: SpringSecurityListener.java    From lemon with Apache License 2.0 5 votes vote down vote up
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));
}
 
Example #12
Source File: SecurityService.java    From eds-starter6-jpa with Apache License 2.0 4 votes vote down vote up
@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);
}
 
Example #13
Source File: UserAuthErrorHandler.java    From eds-starter6-jpa with Apache License 2.0 4 votes vote down vote up
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);
	}
}
 
Example #14
Source File: FailedAuthenticationLogHandler.java    From fredbet with Creative Commons Attribution Share Alike 4.0 International 4 votes vote down vote up
@Override
public void onApplicationEvent(AuthenticationFailureBadCredentialsEvent event) {
	Object username = event.getAuthentication().getPrincipal();
	LOG.info("Failed login using username='{}'", username);
}