@Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { Map<String, Object> result = new HashMap<>(); result.put("isSuccess", false); if (exception instanceof LockedException) { // 如果账户被锁定 logger.info("LoginFailHandler the user is locked!"); result.put("msg", "该用户被锁定!"); } else if (exception instanceof UsernameNotFoundException) { logger.info("LoginSuccessHandler login fail!"); result.put("msg", "该帐号不存在!"); } else { logger.info("LoginFailHandler login fail!"); result.put("msg", "用户名或密码不正确!"); } RequestUtil.responseJson(response, result); }
@Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { // Is already locked? if (exception != null && exception instanceof LockedException) { super.onAuthenticationFailure(request, response, exception); return; } LoginManager.addFailedLoginAttempt(request.getParameter("j_username"), new Date()); if (ApplicationProperty.PasswordReset.isTrue() && User.findByUserName(request.getParameter("j_username")) != null) request.getSession().setAttribute("SUGGEST_PASSWORD_RESET", true); super.onAuthenticationFailure(request, response, exception); }
@Override public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException { if (LOG.isTraceEnabled()) { LOG.trace("Login failed for user {}.", httpServletRequest.getParameter(SecurityConstants.USERNAME_PARAM)); } final LoginStatus status = new LoginStatus(false, false, null, e.getMessage()); if (e instanceof LockedException) { status.setErrorId("login.locked"); } else if (e instanceof DisabledException) { status.setErrorId("login.disabled"); } else if (e instanceof UsernameNotFoundException) { status.setErrorId("login.error"); } mapper.writeValue(httpServletResponse.getOutputStream(), status); }
private void raiseExceptionForErrorCode(int code, NamingException exception) { String hexString = Integer.toHexString(code); Throwable cause = new ActiveDirectoryAuthenticationException(hexString, exception.getMessage(), exception); switch (code) { case PASSWORD_EXPIRED: throw new CredentialsExpiredException(messages.getMessage( "LdapAuthenticationProvider.credentialsExpired", "User credentials have expired"), cause); case ACCOUNT_DISABLED: throw new DisabledException(messages.getMessage( "LdapAuthenticationProvider.disabled", "User is disabled"), cause); case ACCOUNT_EXPIRED: throw new AccountExpiredException(messages.getMessage( "LdapAuthenticationProvider.expired", "User account has expired"), cause); case ACCOUNT_LOCKED: throw new LockedException(messages.getMessage( "LdapAuthenticationProvider.locked", "User account is locked"), cause); default: throw badCredentials(cause); } }
@Override public UsernamePasswordAuthenticationToken authenticate(ConnectionEnvironment connEnv, T authnCtx) throws BadCredentialsException, AuthenticationCredentialsNotFoundException, DisabledException, LockedException, CredentialsExpiredException, AuthenticationServiceException, AccessDeniedException, UsernameNotFoundException { checkEnteredCredentials(connEnv, authnCtx); MidPointPrincipal principal = getAndCheckPrincipal(connEnv, authnCtx.getUsername(), true); UserType userType = principal.getUser(); CredentialsType credentials = userType.getCredentials(); CredentialPolicyType credentialsPolicy = getCredentialsPolicy(principal, authnCtx); if (checkCredentials(principal, authnCtx, connEnv)) { recordPasswordAuthenticationSuccess(principal, connEnv, getCredential(credentials), credentialsPolicy); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(principal, authnCtx.getEnteredCredential(), principal.getAuthorities()); return token; } else { recordPasswordAuthenticationFailure(principal, connEnv, getCredential(credentials), credentialsPolicy, "password mismatch"); throw new BadCredentialsException("web.security.provider.invalid"); } }
@Override public UserType checkCredentials(ConnectionEnvironment connEnv, T authnCtx) throws BadCredentialsException, AuthenticationCredentialsNotFoundException, DisabledException, LockedException, CredentialsExpiredException, AuthenticationServiceException, AccessDeniedException, UsernameNotFoundException { checkEnteredCredentials(connEnv, authnCtx); MidPointPrincipal principal = getAndCheckPrincipal(connEnv, authnCtx.getUsername(), false); UserType userType = principal.getUser(); CredentialsType credentials = userType.getCredentials(); CredentialPolicyType credentialsPolicy = getCredentialsPolicy(principal, authnCtx); if (checkCredentials(principal, authnCtx, connEnv)) { return userType; } else { recordPasswordAuthenticationFailure(principal, connEnv, getCredential(credentials), credentialsPolicy, "password mismatch"); throw new BadCredentialsException("web.security.provider.invalid"); } }
/** * The method is used to extract the error message from the request * @param request The request that contains the exception and error message * @param key The key is used to find the exception attribute in the request. * @return Returns the error message that will be displayed to the user on the login page. */ private String getErrorMessage(final HttpServletRequest request, final String key) { final Exception exception = (Exception) request.getSession().getAttribute(key); String error = ""; if (exception instanceof BadCredentialsException || exception.getCause() instanceof NullPointerException || exception.getCause() instanceof IllegalArgumentException) { LOGGER.debug("Invalid username or password"); error = messageSource.getMessage("general.login.label.invalidcredentials", null, LocaleContextHolder.getLocale()); } else if (exception instanceof LockedException) { LOGGER.debug("User has been locked"); error = messageSource.getMessage("general.login.label.userlocked", null ,LocaleContextHolder.getLocale()); } else if(exception instanceof CredentialsExpiredException){ LOGGER.debug("User has been inactive"); error = messageSource.getMessage("general.login.label.userinactive", null ,LocaleContextHolder.getLocale()); } else { LOGGER.error("Unable to login due to unknown reasons"); LOGGER.error(exception.getMessage(), exception); error = messageSource.getMessage("general.login.label.unknownreason", null ,LocaleContextHolder.getLocale()); } return error; }
/** * Tests the status of the LDAP details and throws an appropriate exception. * * @param dirContextOperations * The context containing user data. * @param username * The username. * @throws AuthenticationException * if the status would prevent logging in */ private void checkAccountStatus(DirContextOperations dirContextOperations, String username) throws AuthenticationException { UserDetails ldapDetails = new LdapUserDetailsMapper() .mapUserFromContext(dirContextOperations, username, new ArrayList<GrantedAuthority>()); if (!ldapDetails.isEnabled()) { throw new DisabledException("LDAP account is disabled."); } if (!ldapDetails.isAccountNonLocked()) { throw new LockedException("LDAP account is locked."); } if (!ldapDetails.isCredentialsNonExpired()) { throw new CredentialsExpiredException("Credentials for LDAP account are expired."); } if (!ldapDetails.isAccountNonExpired()) { throw new AccountExpiredException("LDAP account is expired."); } }
@Override public void onAuthenticationFailure( HttpServletRequest request, HttpServletResponse response, AuthenticationException exception ) throws IOException, ServletException { final String username = request.getParameter( "j_username" ); request.getSession().setAttribute( "username", username ); securityService.registerFailedLogin( username ); I18n i18n = i18nManager.getI18n(); if ( ExceptionUtils.indexOfThrowable( exception, LockedException.class ) != -1) { request.getSession().setAttribute( "LOGIN_FAILED_MESSAGE", i18n.getString( "authentication.message.account.locked" ) ); } else { request.getSession().setAttribute( "LOGIN_FAILED_MESSAGE", i18n.getString( "authentication.message.account.invalid" ) ); } super.onAuthenticationFailure( request, response, exception ); }
@Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { super.onAuthenticationFailure(request, response, exception); if (request.getSession(false) == null && !isAllowSessionCreation()) { return; } request.getSession().setAttribute( LAST_USERNAME_KEY, request.getParameter(LoginDecisionFilter.USERNAME_PARAMETER) ); request.getSession().setAttribute( LAST_PROVIDER_KEY, Strings.isNullOrEmpty(request.getParameter("provider")) ? "internal" : request.getParameter("provider") ); request.getSession().setAttribute(IS_LOCKED, false); if (exception instanceof LdapAuthenticationProcessException) { request.getSession().setAttribute(ERROR_KEY, "login.ldap.internal.user.exists"); } else if (exception instanceof LockedException) { request.getSession().setAttribute(IS_LOCKED, true); } }
private String getErrorMessage(HttpServletRequest request, String key) { Exception exception = (Exception) request.getSession() .getAttribute(key); String error = ""; if (exception instanceof BadCredentialsException) { error = "Invalid username and password!"; } else if (exception instanceof LockedException) { error = exception.getMessage(); } else { error = "Invalid username and password!"; } return error; }
/** * If user with given username exists and is active then authenticates and returns him. Updates the status of the * user when password has been expired. * * @param username username of user * @param authentication data used for authentication * @return the user information */ @Override @Transactional protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) { MotechUser user = motechUsersDao.findByUserName(username); if (user == null) { throw new BadCredentialsException(USER_NOT_FOUND); } else if (!user.isActive()) { throw new LockedException(USER_BLOCKED); } else { if (settingService.getNumberOfDaysToChangePassword() > 0 && Days.daysBetween(user.getSafeLastPasswordChange(), DateUtil.now()).getDays() >= settingService.getNumberOfDaysToChangePassword()) { user.setUserStatus(UserStatus.MUST_CHANGE_PASSWORD); motechUsersDao.update(user); } authentication.setDetails(new MotechUserProfile(user)); return new User(user.getUserName(), user.getPassword(), user.isActive(), true, !UserStatus.MUST_CHANGE_PASSWORD.equals(user.getUserStatus()), !UserStatus.BLOCKED.equals(user.getUserStatus()), authoritiesService.authoritiesFor(user)); } }
@Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { Users user=usersRepository.loadUserByUsername(username); if (user==null){ throw new UsernameNotFoundException("Invalid username/password"); } if (user.getFailedLoginAttempts()>=maxFailedAttempts){ Calendar cal=Calendar.getInstance(); if (user.getLockoutTime()!=null) if (cal.getTimeInMillis()-user.getLockoutTime().getTimeInMillis()>=autoUnlockInterval){ user.setLockoutTime(null); user.setFailedLoginAttemptsToZero(); return user; } throw new LockedException("Your account has excceded maximum failed athentication attempts. Please wait 5 minutes to retry."); } return user; }
/** * Checks if account is active. * @param userAuth user authentication object * @param user user object * @param throwException throw or not * @return the authentication object if {@code user.active == true} */ public static UserAuthentication checkIfActive(UserAuthentication userAuth, User user, boolean throwException) { if (userAuth == null || user == null || user.getIdentifier() == null) { if (throwException) { throw new BadCredentialsException("Bad credentials."); } else { logger.error("Bad credentials."); return null; } } else if (!user.getActive()) { if (throwException) { throw new LockedException("Account " + user.getId() + " is locked."); } else { logger.error("Account {} is locked.", user.getId()); return null; } } return userAuth; }
@Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { String userName = request.getParameter(usernamePasswordAuthenticationFilter.getUsernameParameter()); log.info("onAuthenticationFailure- username={}, exceptionClass={}", userName, exception.getClass().getName()); String parameter = "unknown"; if (exception instanceof UsernameNotFoundException) { parameter = "usernameEmpty"; } else if (exception instanceof BadCredentialsException) { parameter = "badCredential"; } else if (exception instanceof LockedException) { parameter = "userLocked"; } response.sendRedirect("login?error=" + parameter); }
@Bean public AuthenticationFailureHandler authenticationFailureHandler() { ExceptionMappingAuthenticationFailureHandler failureHandler = new ExceptionMappingAuthenticationFailureHandler(); Map<String, String> failureUrlMap = new HashMap<>(); failureUrlMap.put(BadCredentialsException.class.getName(), LoginAuthenticationFailureHandler.PASS_ERROR_URL); failureUrlMap.put(CaptchaException.class.getName(), LoginAuthenticationFailureHandler.CODE_ERROR_URL); failureUrlMap.put(AccountExpiredException.class.getName(), LoginAuthenticationFailureHandler.EXPIRED_URL); failureUrlMap.put(LockedException.class.getName(), LoginAuthenticationFailureHandler.LOCKED_URL); failureUrlMap.put(DisabledException.class.getName(), LoginAuthenticationFailureHandler.DISABLED_URL); failureHandler.setExceptionMappings(failureUrlMap); return failureHandler; }
protected AuthResponse(Exception e){ super(e); this.setService(SERVICE_NAME); if (e instanceof AuthenticationException) { if (e instanceof UsernameNotFoundException) { this.setErrorCode(CodeUsernameNotFound); } else if (e instanceof DisabledException) { this.setErrorCode(CodeDisabled); } else if (e instanceof LockedException) { this.setErrorCode(CodeLocked); } else if (e instanceof BadCredentialsException) { this.setErrorCode(CodeBadCredentials); } else if (e instanceof CredentialsExpiredException) { this.setErrorCode(CodeCredentialsExpired); } else if (e instanceof BadCaptchaException) { this.setErrorCode(CodeBadCaptcha); } else if (e instanceof SmsProviderException){ this.setErrorCode(CodeSmsProvide); } else if (e instanceof UserExistException){ this.setErrorCode(CodeSmsProvide); } else if (e instanceof UnauthorizedException){ this.setErrorCode(CodeUnauthorized); } else { this.setErrorCode(CodeAuthenticationFailed); } } }
void verifyAccountStatus(Person user) { if (user.isLocked()) { throw new LockedException("Account is locked."); } if (!user.isEnabled()) { throw new DisabledException("Account is disabled."); } }
@Test public void authenticationFailureReturnsLoginStatusWithErrorInfoOnAccountLocked() throws Exception { final MockHttpServletRequest request = AuthenticationSuccessTest.request(); final MockHttpServletResponse response = AuthenticationSuccessTest.response(); final String msg = "Account is locked."; failure.onAuthenticationFailure(request, response, new LockedException(msg)); final LoginStatus status = mapper.readValue(response.getContentAsString(), LoginStatus.class); assertFalse(status.isSuccess()); assertFalse(status.isLoggedIn()); assertNull(status.getUsername()); assertEquals(msg, status.getErrorMessage()); assertEquals("login.locked", status.getErrorId()); }
@Override public Authentication authenticate(final Authentication authentication) { final JwtAuthenticationToken authRequest = (JwtAuthenticationToken) authentication; final Jws<Claims> claimsJws = parserAndVerify(authRequest); if (claimsJws.getBody().getExpiration() == null) { throw new BadCredentialsException("Only temporary JWT supported"); } final String username = claimsJws.getBody().getSubject(); final UserDetails userDetails; try { userDetails = userDetailsService.loadUserByUsername(username); } catch (final UsernameNotFoundException notFound) { throw new BadCredentialsException("Bad credentials"); } if (!userDetails.isAccountNonLocked()) { throw new LockedException("User account is locked"); } if (!userDetails.isEnabled()) { throw new DisabledException("User is disabled"); } if (!userDetails.isAccountNonExpired()) { throw new AccountExpiredException("User account has expired"); } if (!userDetails.isCredentialsNonExpired()) { throw new CredentialsExpiredException("User credentials have expired"); } LOG.info("Successful JWT authentication for username={}", userDetails.getUsername()); return JwtAuthenticationToken.createAuthenticated(userDetails, authRequest.getDetails()); }
@ResponseStatus(HttpStatus.UNAUTHORIZED) @ExceptionHandler({AccessDeniedException.class, LockedException.class, DisabledException.class, CredentialsExpiredException.class}) @ResponseBody ResultDto handleUserException(HttpServletRequest req, Exception ex) { return new ResultDto(ex.getLocalizedMessage()); }
@Override public Board updateBoard(String id, BoardUpdateDto boardUpdateDto) { User user = getAuthorizedUser(); Board board = boardRepository.findOne(id); if (board != null) { if (!user.hasRole(UserRole.ADMIN) && !board.getOwner().equals(user) && !board.getUsers().contains(user)) { log.error("User {} does not have rights to alter board {}.", user.getUsername(), id); throw new AccessDeniedException("User is not allowed to alter board."); } board.setName(boardUpdateDto.getName()); board.setOwner(userService.loadUserByUsername(boardUpdateDto.getOwner().getUsername())); if (boardUpdateDto.getMembers() != null) { Set<User> members = new LinkedHashSet<>(); boardUpdateDto.getMembers().forEach(d -> { try { members.add(userService.loadUserByUsername(d.getUsername())); } catch (AccessDeniedException | LockedException | DisabledException | CredentialsExpiredException e) { log.warn(e.getMessage()); } }); board.setUsers(members); } boardRepository.save(board); } else { log.info("No board with given id {} found.", id); throw new BoardNotFoundException("Board with id " + id + " not found."); } return board; }
private boolean checkCredentials(MidPointPrincipal principal, T authnCtx, ConnectionEnvironment connEnv) { UserType userType = principal.getUser(); CredentialsType credentials = userType.getCredentials(); if (credentials == null || getCredential(credentials) == null) { recordAuthenticationFailure(principal, connEnv, "no credentials in user"); throw new AuthenticationCredentialsNotFoundException("web.security.provider.invalid"); } CredentialPolicyType credentialsPolicy = getCredentialsPolicy(principal, authnCtx); // Lockout if (isLockedOut(getCredential(credentials), credentialsPolicy)) { recordAuthenticationFailure(principal, connEnv, "password locked-out"); throw new LockedException("web.security.provider.locked"); } if (suportsAuthzCheck()) { // Authorizations if (!hasAnyAuthorization(principal)) { recordAuthenticationFailure(principal, connEnv, "no authorizations"); throw new DisabledException("web.security.provider.access.denied"); } } // Password age checkPasswordValidityAndAge(connEnv, principal, getCredential(credentials), credentialsPolicy); return passwordMatches(connEnv, principal, getCredential(credentials), authnCtx); }
/** * Special-purpose method used for Web Service authentication based on javax.security callbacks. * * In that case there is no reasonable way how to reuse existing methods. Therefore this method is NOT part of the * AuthenticationEvaluator interface. It is mostly a glue to make the old Java security code work. */ public String getAndCheckUserPassword(ConnectionEnvironment connEnv, String enteredUsername) throws AuthenticationCredentialsNotFoundException, DisabledException, LockedException, CredentialsExpiredException, AuthenticationServiceException, AccessDeniedException, UsernameNotFoundException { MidPointPrincipal principal = getAndCheckPrincipal(connEnv, enteredUsername, true); UserType userType = principal.getUser(); CredentialsType credentials = userType.getCredentials(); if (credentials == null) { recordAuthenticationFailure(principal, connEnv, "no credentials in user"); throw new AuthenticationCredentialsNotFoundException("web.security.provider.invalid"); } PasswordType passwordType = credentials.getPassword(); SecurityPolicyType securityPolicy = principal.getApplicableSecurityPolicy(); PasswordCredentialsPolicyType passwordCredentialsPolicy = SecurityUtil.getEffectivePasswordCredentialsPolicy(securityPolicy); // Lockout if (isLockedOut(passwordType, passwordCredentialsPolicy)) { recordAuthenticationFailure(principal, connEnv, "password locked-out"); throw new LockedException("web.security.provider.locked"); } // Authorizations if (!hasAnyAuthorization(principal)) { recordAuthenticationFailure(principal, connEnv, "no authorizations"); throw new AccessDeniedException("web.security.provider.access.denied"); } // Password age checkPasswordValidityAndAge(connEnv, principal, passwordType.getValue(), passwordType.getMetadata(), passwordCredentialsPolicy); return getPassword(connEnv, principal, passwordType.getValue()); }
@Test public void test132PasswordLoginLockedoutGoodPassword() throws Exception { final String TEST_NAME = "test132PasswordLoginLockedoutGoodPassword"; TestUtil.displayTestTile(TEST_NAME); // GIVEN ConnectionEnvironment connEnv = createConnectionEnvironment(); // WHEN TestUtil.displayWhen(TEST_NAME); try { getAuthenticationEvaluator().authenticate(connEnv, getAuthenticationContext(USER_JACK_USERNAME, getGoodPasswordJack())); AssertJUnit.fail("Unexpected success"); } catch (LockedException e) { // This is expected // THEN TestUtil.displayThen(TEST_NAME); display("expected exception", e); assertLockedException(e, USER_JACK_USERNAME); } PrismObject<UserType> userAfter = getUser(USER_JACK_OID); display("user after", userAfter); assertFailedLogins(userAfter, 3); assertUserLockout(userAfter, LockoutStatusType.LOCKED); }
@Test public void test133PasswordLoginLockedoutBadPassword() throws Exception { final String TEST_NAME = "test133PasswordLoginLockedoutBadPassword"; TestUtil.displayTestTile(TEST_NAME); // GIVEN ConnectionEnvironment connEnv = createConnectionEnvironment(); // WHEN TestUtil.displayWhen(TEST_NAME); try { getAuthenticationEvaluator().authenticate(connEnv, getAuthenticationContext(USER_JACK_USERNAME, getBadPasswordJack())); AssertJUnit.fail("Unexpected success"); } catch (LockedException e) { // This is expected // THEN TestUtil.displayThen(TEST_NAME); display("expected exception", e); // this is important. The exception should give no indication whether the password is // good or bad assertLockedException(e, USER_JACK_USERNAME); } PrismObject<UserType> userAfter = getUser(USER_JACK_OID); display("user after", userAfter); assertFailedLogins(userAfter, 3); assertUserLockout(userAfter, LockoutStatusType.LOCKED); }
@Test public void test137PasswordLoginLockedoutGoodPasswordAgain() throws Exception { final String TEST_NAME = "test137PasswordLoginLockedoutGoodPasswordAgain"; TestUtil.displayTestTile(TEST_NAME); // GIVEN ConnectionEnvironment connEnv = createConnectionEnvironment(); // WHEN TestUtil.displayWhen(TEST_NAME); try { getAuthenticationEvaluator().authenticate(connEnv, getAuthenticationContext(USER_JACK_USERNAME, getGoodPasswordJack())); AssertJUnit.fail("Unexpected success"); } catch (LockedException e) { // This is expected // THEN TestUtil.displayThen(TEST_NAME); display("expected exception", e); assertLockedException(e, USER_JACK_USERNAME); } PrismObject<UserType> userAfter = getUser(USER_JACK_OID); display("user after", userAfter); assertFailedLogins(userAfter, 3); assertUserLockout(userAfter, LockoutStatusType.LOCKED); }
public CachedUser getUser(String userId, boolean throwExceptionOnNotFound, boolean throwExceptionOnInactive, boolean checkValidity) { try { // The cache is a LoadingCache and will fetch the value itself CachedUser cachedUser = userCache.get(userId); return cachedUser; } catch (ExecutionException e) { return null; } catch (UncheckedExecutionException uee) { // Some magic with the exceptions is needed: // the exceptions like UserNameNotFound and Locked cannot // bubble up, since Spring security will react on them otherwise if (uee.getCause() instanceof RuntimeException) { RuntimeException runtimeException = (RuntimeException) uee.getCause(); if (runtimeException instanceof UsernameNotFoundException) { if (throwExceptionOnNotFound) { throw runtimeException; } else { return null; } } if (runtimeException instanceof LockedException) { if (throwExceptionOnNotFound) { throw runtimeException; } else { return null; } } } throw uee; } }
@ResponseStatus(HttpStatus.UNAUTHORIZED) // 401 @ExceptionHandler(LockedException.class) @ResponseBody public ErrorInfo handleLockedUser(LockedException e) { ErrorInfo result = new ErrorInfo(e.getMessage()); result.setMessageKey(INACTIVE_USER_MESSAGE_KEY); return result; }
/** * Creates a descriptive error message for the authentication exception. * * @param request * the request * @param e * the exception * @return the error message */ protected String createErrorMessage(HttpServletRequest request, AuthenticationException e) { String message; if (e instanceof UserAccountPermanentlyLockedException) { message = MessageHelper.getText(request, "login.external.error.userPermLocked"); } else if (e instanceof UserAccountTemporarilyLockedException) { message = MessageHelper.getText(request, "login.external.error.userTempLocked", new String[] { ((UserAccountTemporarilyLockedException) e) .getFormattedLockedTimeout( SessionHandler.instance().getCurrentLocale(request), UserManagementHelper.getEffectiveUserTimeZone((Long) null)) }); } else if (e instanceof LockedException) { message = MessageHelper.getText(request, "login.external.error.notactivated"); } else if (e instanceof TermsOfUseNotAcceptedException) { message = MessageHelper.getText(request, "login.error.termsOfUseNotAccepted"); } else if (e instanceof AuthenticationServiceException) { Throwable t = e.getCause(); if (t != null && t instanceof EmailAlreadyExistsException) { message = MessageHelper.getText(request, "login.external.error.email.used"); } else { message = MessageHelper.getText(request, "login.external.error.failed"); } } else { message = MessageHelper.getText(request, "login.external.error.failed"); } return message; }
private void assertUserNotLocked(String username) { if (isLockMechanismDisabled()) { return; } Date logindate = lastFailedLogin.get(username); if (logindate != null && isWaitTimeOver(logindate)) { accessCounter.remove(username); lastFailedLogin.remove(username); } if (accessCounter.get(username) != null && accessCounter.get(username) >= maxLoginFailures) { throw new LockedException("The user '" + username + "' is temporary locked."); } }
@Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { T user = fetUserByUserName(username); if(!UserStatus.NORMAL.name().equals(user.getStatus())){ throw new LockedException("用户状态异常:"+user.getStatusName()); } List<GrantedAuthority> authes = fetchUserGrantedAuthorities(user); UserDetails userDetail = buildUserDetail(user, authes); return userDetail; }