类org.springframework.security.authentication.LockedException源码实例Demo

下面列出了怎么用org.springframework.security.authentication.LockedException的API类实例代码及写法,或者点击链接到github查看源代码。

@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 ) );
}
 
@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 );
}
 
@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);
    }
}
 
@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);
}
 
源代码5 项目: para   文件: SecurityUtils.java
/**
 * 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;
}
 
@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);
}
 
源代码7 项目: Spring-Boot-Book   文件: SysSecurityService.java
@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;
}
 
源代码8 项目: Spring-Boot-Book   文件: SysSecurityService.java
@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;
}
 
源代码9 项目: Spring-Boot-Book   文件: SysSecurityService.java
@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;
}
 
源代码10 项目: FEBS-Cloud   文件: FebsWebLoginFailureHandler.java
@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);
}
 
@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"));
    }
}
 
源代码12 项目: activiti6-boot2   文件: UserCacheImpl.java
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;
}
 
源代码14 项目: zhcet-web   文件: LoginAttemptService.java
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);
}
 
源代码15 项目: zhcet-web   文件: CustomAuthenticationProvider.java
@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;
}
 
@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());
}
 
源代码17 项目: spring-boot-cookbook   文件: SecurityConfig.java
@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;
}
 
源代码18 项目: flowable-engine   文件: UserCacheImpl.java
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;
    }
}
 
源代码19 项目: flowable-engine   文件: UserCacheImpl.java
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;
}
 
源代码21 项目: onetwo   文件: ExceptionUserChecker.java
public void checkUser(String userName){
	AtomicInteger errorTimes = getExceptionTimesByUser(userName);
	int times = errorTimes.get();
	if(times>=maxLoginTimes){
		throw new LockedException("登录错误超过"+maxLoginTimes+"次,请稍后尝试!");
	}
}
 
源代码22 项目: osiam   文件: InternalAuthenticationProvider.java
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 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() );
}
 
@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 ());
}
 
 同包方法