org.springframework.security.authentication.LockedException Java Examples
The following examples show how to use
org.springframework.security.authentication.LockedException.
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: SecurityAuthenticationFailureHandler.java From WebApplication-Project-Skeleton with MIT License | 6 votes |
@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); }
Example #2
Source File: SecurityUtils.java From para with Apache License 2.0 | 6 votes |
/** * 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.debug("Bad credentials. {}", userAuth); return null; } } else if (!user.getActive()) { if (throwException) { throw new LockedException("Account " + user.getId() + " (" + user.getAppid() + "/" + user.getIdentifier() + ") is locked."); } else { logger.warn("Account {} ({}/{}) is locked.", user.getId(), user.getAppid(), user.getIdentifier()); return null; } } return userAuth; }
Example #3
Source File: UniTimeAuthenticationFailureHandler.java From unitime with Apache License 2.0 | 6 votes |
@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("username"), new Date()); if (ApplicationProperty.PasswordReset.isTrue() && User.findByUserName(request.getParameter("username")) != null) request.getSession().setAttribute("SUGGEST_PASSWORD_RESET", true); super.onAuthenticationFailure(request, response, exception); }
Example #4
Source File: OsiamCachingAuthenticationFailureHandler.java From osiam with MIT License | 6 votes |
@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); } }
Example #5
Source File: CustomExceptionMappingAuthenticationFailureHandler.java From dhis2-core with BSD 3-Clause "New" or "Revised" License | 6 votes |
@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 ); 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 ); }
Example #6
Source File: BasicAuthenticationEntryPoint.java From dhis2-core with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Override public void commence( HttpServletRequest request, HttpServletResponse response, AuthenticationException authException ) throws IOException { String message; if ( ExceptionUtils.indexOfThrowable( authException, LockedException.class ) != -1 ) { message = "Account locked" ; } else { message = "Unauthorized"; } response.setStatus( HttpServletResponse.SC_UNAUTHORIZED ); response.setContentType( MediaType.APPLICATION_JSON_VALUE ); renderService.toJson( response.getOutputStream(), WebMessageUtils.unathorized( message ) ); }
Example #7
Source File: UserCacheImpl.java From flowable-engine with Apache License 2.0 | 5 votes |
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; } }
Example #8
Source File: InternalAuthenticationProvider.java From osiam with MIT License | 5 votes |
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."); } }
Example #9
Source File: ExceptionUserChecker.java From onetwo with Apache License 2.0 | 5 votes |
public void checkUser(String userName){ AtomicInteger errorTimes = getExceptionTimesByUser(userName); int times = errorTimes.get(); if(times>=maxLoginTimes){ throw new LockedException("登录错误超过"+maxLoginTimes+"次,请稍后尝试!"); } }
Example #10
Source File: RestExceptionHandlerAdvice.java From flowable-engine with Apache License 2.0 | 5 votes |
@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; }
Example #11
Source File: SysSecurityService.java From Spring-Boot-Book with Apache License 2.0 | 5 votes |
@Override public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException { SysUser user = sysUserRepository.findByName(name); if (user == null) { throw new UsernameNotFoundException("用户名不存在"); } else if (!user.getEnabled()) { //被锁定,无法登录 throw new LockedException("用户被锁定"); } System.out.println(user.getEnabled()); return user; }
Example #12
Source File: UserCacheImpl.java From flowable-engine with Apache License 2.0 | 5 votes |
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; } }
Example #13
Source File: SecurityConfig.java From spring-boot-cookbook with Apache License 2.0 | 5 votes |
@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; }
Example #14
Source File: OneOffSpringCommonFrameworkExceptionHandlerListenerTest.java From backstopper with Apache License 2.0 | 5 votes |
@DataProvider public static List<List<Throwable>> unauthorized401ExceptionsDataProvider() { return Stream.<Throwable>of( new BadCredentialsException("foo"), new InsufficientAuthenticationException("foo"), new AuthenticationCredentialsNotFoundException("foo"), new LockedException("foo"), new DisabledException("foo"), new CredentialsExpiredException("foo"), new AccountExpiredException("foo"), new UsernameNotFoundException("foo"), new RemoteAuthenticationException("foo") ).map(Collections::singletonList) .collect(Collectors.toList()); }
Example #15
Source File: CustomAuthenticationProvider.java From zhcet-web with Apache License 2.0 | 5 votes |
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String userId = (String) authentication.getPrincipal(); CustomAuthenticationDetails details = (CustomAuthenticationDetails) authentication.getDetails(); boolean isBlocked = loginAttemptService.isBlocked(userId); if (isBlocked) { log.debug("User account is locked"); throw new LockedException(messages.getMessage( "AbstractUserDetailsAuthenticationProvider.locked", "User account is locked")); } Authentication authenticated = super.authenticate(authentication); UserAuth userAuth = (UserAuth) authenticated.getPrincipal(); if (!userAuth.isUsing2fa()) return authenticated; String code = details.getTotpCode(); String secret = userAuth.getTotpSecret(); if (secret == null || code == null) { throw new BadCredentialsException("OTP was not provided"); } else if (TwoFAService.isInvalidOtp(secret, code)) { throw new BadCredentialsException("OTP was incorrect. Please try again"); } return authenticated; }
Example #16
Source File: LoginAttemptService.java From zhcet-web with Apache License 2.0 | 5 votes |
public void addErrors(Model model, HttpServletRequest request) { String message = "Username or Password is incorrect!"; Object exception = request.getSession().getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION); Object rawUsername = request.getSession().getAttribute(UsernameAuthenticationFailureHandler.USERNAME); // If exception is null, show default message if (exception != null && rawUsername instanceof String) { String coolDownPeriod = getBlockDuration() + " " + LoginAttemptService.TIME_UNIT; String username = (String) rawUsername; if (exception instanceof LockedException || isBlocked(username)) { message = "User blocked for <strong>" + coolDownPeriod + "</strong> since last wrong login attempt"; } else if (exception instanceof BadCredentialsException) { String tries = String.format("%d out of %d tries left!", triesLeft(username), getMaxRetries()); String coolDown = "User will be blocked for " + coolDownPeriod + " after all tries are exhausted"; String errorMessage = extractMessage((BadCredentialsException) exception, message); // If the error is about OTP, tell frontend that OTP is required if (errorMessage.toLowerCase().contains("otp")) { model.addAttribute("otp_required", true); } message = errorMessage + "<br><strong>" + tries + "</strong> " + coolDown; } else if (exception instanceof DisabledException) { message = "User is disabled from site"; } } model.addAttribute("login_error", message); }
Example #17
Source File: RestExceptionHandlerAdvice.java From activiti6-boot2 with Apache License 2.0 | 5 votes |
@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; }
Example #18
Source File: UserCacheImpl.java From activiti6-boot2 with Apache License 2.0 | 5 votes |
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; } }
Example #19
Source File: AbstractUserDetailsAuthenticationProvider.java From Taroco with Apache License 2.0 | 5 votes |
@Override public void check(UserDetails user) { if (!user.isAccountNonLocked()) { log.debug("User account is locked"); throw new LockedException(AbstractUserDetailsAuthenticationProvider.this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.locked", "User account is locked")); } else if (!user.isEnabled()) { log.debug("User account is disabled"); throw new DisabledException(AbstractUserDetailsAuthenticationProvider.this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.disabled", "User is disabled")); } else if (!user.isAccountNonExpired()) { log.debug("User account is expired"); throw new AccountExpiredException(AbstractUserDetailsAuthenticationProvider.this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.expired", "User account has expired")); } }
Example #20
Source File: FebsWebLoginFailureHandler.java From FEBS-Cloud with Apache License 2.0 | 5 votes |
@Override public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException exception) throws IOException { String message; if (exception instanceof BadCredentialsException) { message = "用户名或密码错误!"; } else if (exception instanceof LockedException) { message = "用户已被锁定!"; } else { message = "认证失败,请联系网站管理员!"; } FebsResponse febsResponse = new FebsResponse().message(message); FebsUtil.makeFailureResponse(httpServletResponse, febsResponse); }
Example #21
Source File: SysSecurityService.java From Spring-Boot-Book with Apache License 2.0 | 5 votes |
@Override public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException { SysUser user = sysUserRepository.findByName(name); if (user == null) { throw new UsernameNotFoundException("用户名不存在"); } else if (!user.getEnabled()) { //被锁定,无法登录 throw new LockedException("用户被锁定"); } System.out.println(user.getEnabled()); return user; }
Example #22
Source File: SysSecurityService.java From Spring-Boot-Book with Apache License 2.0 | 5 votes |
@Override public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException { SysUser user = sysUserRepository.findByName(name); if (user == null) { throw new UsernameNotFoundException("用户名不存在"); } else if (!user.getEnabled()) { //被锁定,无法登录 throw new LockedException("用户被锁定"); } System.out.println(user.getEnabled()); return user; }
Example #23
Source File: TwoFactorAuthenticationProvider.java From dhis2-core with BSD 3-Clause "New" or "Revised" License | 4 votes |
@Override public Authentication authenticate( Authentication auth ) throws AuthenticationException { log.info( String.format( "Login attempt: %s", auth.getName() ) ); String username = auth.getName(); UserCredentials userCredentials = userService.getUserCredentialsWithEagerFetchAuthorities( username ); if ( userCredentials == null ) { throw new BadCredentialsException( "Invalid username or password" ); } // Initialize all required properties of user credentials since these will become detached userCredentials.getAllAuthorities(); // ------------------------------------------------------------------------- // Check two-factor authentication // ------------------------------------------------------------------------- if ( userCredentials.isTwoFA() ) { TwoFactorWebAuthenticationDetails authDetails = (TwoFactorWebAuthenticationDetails) auth.getDetails(); // ------------------------------------------------------------------------- // Check whether account is locked due to multiple failed login attempts // ------------------------------------------------------------------------- if ( authDetails == null ) { log.info( "Missing authentication details in authentication request." ); throw new PreAuthenticatedCredentialsNotFoundException( "Missing authentication details in authentication request." ); } String ip = authDetails.getIp(); String code = StringUtils.deleteWhitespace( authDetails.getCode() ); if ( securityService.isLocked( username ) ) { log.info( String.format( "Temporary lockout for user: %s and IP: %s", username, ip ) ); throw new LockedException( String.format( "IP is temporarily locked: %s", ip ) ); } if ( !LongValidator.getInstance().isValid( code ) || !SecurityUtils.verify( userCredentials, code ) ) { log.info( String.format( "Two-factor authentication failure for user: %s", userCredentials.getUsername() ) ); throw new BadCredentialsException( "Invalid verification code" ); } } // ------------------------------------------------------------------------- // Delegate authentication downstream, using UserCredentials as principal // ------------------------------------------------------------------------- Authentication result = super.authenticate( auth ); // Put detached state of the user credentials into the session as user // credentials must not be updated during session execution userCredentials = SerializationUtils.clone( userCredentials ); // Initialize cached authorities userCredentials.isSuper(); userCredentials.getAllAuthorities(); return new UsernamePasswordAuthenticationToken( userCredentials, result.getCredentials(), result.getAuthorities() ); }
Example #24
Source File: DefaultAuthenticationProvider.java From DataHubSystem with GNU Affero General Public License v3.0 | 4 votes |
@Override @Transactional (propagation=Propagation.REQUIRED) public Authentication authenticate (Authentication authentication) throws AuthenticationException { String username = (String) authentication.getPrincipal (); String password = (String) authentication.getCredentials (); String ip = "unknown"; if (authentication.getDetails () instanceof WebAuthenticationDetails) { ip = ((WebAuthenticationDetails)authentication.getDetails ()) .getRemoteAddress (); } LOGGER.info ("Connection attempted by '" + authentication.getName () + "' from " + ip); User user = userService.getUserNoCheck (username); if (user == null || user.isDeleted ()) { throw new BadCredentialsException (errorMessage); } PasswordEncryption encryption = user.getPasswordEncryption (); if ( !encryption.equals (PasswordEncryption.NONE)) { MessageDigest md; try { md = MessageDigest.getInstance (encryption.getAlgorithmKey ()); password = new String ( Hex.encode (md.digest (password.getBytes ("UTF-8")))); } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) { throw new BadCredentialsException ("Authentication process failed", e); } } if ( !user.getPassword ().equals (password)) { LOGGER.warn ( new Message (MessageType.USER, "Connection refused for '" + username + "' from " + ip + " : error in login/password combination")); throw new BadCredentialsException (errorMessage); } for (AccessRestriction restriction : user.getRestrictions ()) { LOGGER.warn ("Connection refused for '" + username + "' from " + ip + " : account is locked (" + restriction.getBlockingReason () + ")"); throw new LockedException (restriction.getBlockingReason ()); } LOGGER.info ("Connection success for '" + username + "' from " + ip); return new ValidityAuthentication (user, user.getAuthorities ()); }