java类org.springframework.security.authentication.LockedException的实例源码

LoginFailHandler.java 文件源码 项目:minsx-authorization-server 阅读 30 收藏 0 点赞 0 评论 0
@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);
}
UniTimeAuthenticationFailureHandler.java 文件源码 项目:unitimes 阅读 25 收藏 0 点赞 0 评论 0
@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);
}
AuthenticationFailure.java 文件源码 项目:reporting-tool 阅读 30 收藏 0 点赞 0 评论 0
@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);
}
ActiveDirectoryAliasLdapAuthenticationProvider.java 文件源码 项目:parking-api 阅读 28 收藏 0 点赞 0 评论 0
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);
    }
}
AuthenticationEvaluatorImpl.java 文件源码 项目:engerek 阅读 30 收藏 0 点赞 0 评论 0
@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");
    }
}
AuthenticationEvaluatorImpl.java 文件源码 项目:engerek 阅读 30 收藏 0 点赞 0 评论 0
@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");
    }
}
LoginController.java 文件源码 项目:castlemock 阅读 53 收藏 0 点赞 0 评论 0
/**
 * 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;
}
LdapAuthenticator.java 文件源码 项目:communote-server 阅读 38 收藏 0 点赞 0 评论 0
/**
 * 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.");
    }
}
CustomExceptionMappingAuthenticationFailureHandler.java 文件源码 项目:dhis2-core 阅读 21 收藏 0 点赞 0 评论 0
@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 );
}
OsiamCachingAuthenticationFailureHandler.java 文件源码 项目:auth-server 阅读 26 收藏 0 点赞 0 评论 0
@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);
    }
}
MainController.java 文件源码 项目:hotel_shop 阅读 36 收藏 0 点赞 0 评论 0
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;
    }
OsiamCachingAuthenticationFailureHandler.java 文件源码 项目:osiam 阅读 30 收藏 0 点赞 0 评论 0
@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);
    }
}
UniTimeAuthenticationFailureHandler.java 文件源码 项目:unitime 阅读 33 收藏 0 点赞 0 评论 0
@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);
}
MotechAuthenticationProvider.java 文件源码 项目:motech 阅读 32 收藏 0 点赞 0 评论 0
/**
 * 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));
    }
}
AccountUserDetailsService.java 文件源码 项目:ds4p 阅读 37 收藏 0 点赞 0 评论 0
@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;
}
AuthenticationEvaluatorImpl.java 文件源码 项目:midpoint 阅读 28 收藏 0 点赞 0 评论 0
@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");
    }
}
AuthenticationEvaluatorImpl.java 文件源码 项目:midpoint 阅读 31 收藏 0 点赞 0 评论 0
@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");
    }
}
SecurityUtils.java 文件源码 项目:para 阅读 39 收藏 0 点赞 0 评论 0
/**
 * 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;
}
SecurityAuthenticationFailureHandler.java 文件源码 项目:WebApplication-Project-Skeleton 阅读 28 收藏 0 点赞 0 评论 0
@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);
}
AuthenticationEvaluatorImpl.java 文件源码 项目:midpoint 阅读 30 收藏 0 点赞 0 评论 0
@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");
    }
}
AuthenticationEvaluatorImpl.java 文件源码 项目:midpoint 阅读 21 收藏 0 点赞 0 评论 0
@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");
    }
}
FormLoginSecurityConfig.java 文件源码 项目:sns-todo 阅读 30 收藏 0 点赞 0 评论 0
@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;
}
AuthResponse.java 文件源码 项目:parkingcloud 阅读 27 收藏 0 点赞 0 评论 0
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);
        }
    }
}
AbstractAuthenticationProvider.java 文件源码 项目:reporting-tool 阅读 29 收藏 0 点赞 0 评论 0
void verifyAccountStatus(Person user) {
    if (user.isLocked()) {
        throw new LockedException("Account is locked.");
    }
    if (!user.isEnabled()) {
        throw new DisabledException("Account is disabled.");
    }
}
AuthenticationFailureTest.java 文件源码 项目:reporting-tool 阅读 24 收藏 0 点赞 0 评论 0
@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());
}
JwtAuthenticationProvider.java 文件源码 项目:oma-riista-web 阅读 33 收藏 0 点赞 0 评论 0
@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());
}
ExceptionControllerAdvice.java 文件源码 项目:kanbanboard 阅读 34 收藏 0 点赞 0 评论 0
@ResponseStatus(HttpStatus.UNAUTHORIZED)
@ExceptionHandler({AccessDeniedException.class, LockedException.class,
        DisabledException.class, CredentialsExpiredException.class})
@ResponseBody
ResultDto handleUserException(HttpServletRequest req, Exception ex) {
    return new ResultDto(ex.getLocalizedMessage());
}
BoardServiceImpl.java 文件源码 项目:kanbanboard 阅读 26 收藏 0 点赞 0 评论 0
@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;
}
AuthenticationEvaluatorImpl.java 文件源码 项目:engerek 阅读 25 收藏 0 点赞 0 评论 0
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);
}
AuthenticationEvaluatorImpl.java 文件源码 项目:engerek 阅读 29 收藏 0 点赞 0 评论 0
/**
 * 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());
}


问题


面经


文章

微信
公众号

扫码关注公众号