Java 类org.springframework.security.authentication.AccountExpiredException 实例源码

项目:parking-api    文件:ActiveDirectoryAliasLdapAuthenticationProvider.java   
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);
    }
}
项目:communote-server    文件:LdapAuthenticator.java   
/**
 * 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.");
    }
}
项目:oma-riista-web    文件:JwtAuthenticationProvider.java   
@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());
}
项目:SIRME    文件:BSAuthenticationProvider.java   
@Override
public Authentication authenticate(Authentication auth)
        throws AuthenticationException {

    String principal = (String) auth.getPrincipal();
       String password = (String) auth.getCredentials();

       //Transformacion de password a MD5
       String passwordMD5 = getPasswordEncoder().encodePassword(password, null);        

    UserDetails details = getUserDetailsService().loadUserByUsername(principal);
       if (principal == null || principal.trim().length() == 0) {
        throw new BadCredentialsException("Usuario obligatorio", null);
       } else if (password == null || password.trim().length() == 0) {
        throw new BadCredentialsException("Password obligatoria", null);
       } else if (details == null || !details.getPassword().equals(passwordMD5)) {
        throw new BadCredentialsException("Usuario y/o password no validos", null);
    } else if (!details.isEnabled()) {
        throw new DisabledException("La cuenta ha sido inhabilitada. Contacte con el administrador del sistema.");
    } else if (!details.isAccountNonLocked()) {
        throw new LockedException("La cuenta ha sido bloqueada. Contacte con el administrador del sistema.");
    } else if (!details.isAccountNonExpired()) {
        throw new AccountExpiredException("La cuenta ha caducado. Contacte con el administrador del sistema.");
    } else if (!details.isCredentialsNonExpired()) {
        throw new CredentialsExpiredException("La password ha caducado. Contacte con el administrador del sistema.");
    }

       try {
        usersService.updateDateAccess( auth.getPrincipal().toString() );
    } catch (ValidationException | TransactionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

        return new UsernamePasswordAuthenticationToken(details, passwordMD5, details.getAuthorities());
}
项目:communote-server    文件:ExternalAuthenticationProvider.java   
/**
 * Evaluates the caught AuthenticationException and updates the user (e.g. disable his account)
 * if necessary and possible. This will only be possible if the authentication's principal has a
 * name (i.e. a.getName() != null).
 *
 * @param e
 *            the exception
 * @param userIdentifier
 *            identifier (email or alias) of the user for whom the authentication was attempted
 * @return the exception that should be rethrown
 * @throws AuthenticationException
 *             the passed exception
 * @throws EmailAlreadyExistsException
 *             when the new email exists
 * @throws AliasAlreadyExistsException
 *             when the new alias exists
 * @throws EmailValidationException
 *             when the email cannot be validated
 * @throws UserActivationValidationException
 *             in case the user cannot be updated
 * @throws InvalidUserStatusTransitionException
 *             when changing the user status is not possible
 * @throws NoClientManagerLeftException
 *             when changing the user status is not possible because the last client manager
 *             would be logged out
 * @throws PermanentIdMissmatchException
 *             when the permanentID changed
 */

private AuthenticationException handleAuthenticationException(AuthenticationException e,
        String userIdentifier) throws AuthenticationException, EmailAlreadyExistsException,
        EmailValidationException, AliasAlreadyExistsException,
        UserActivationValidationException, InvalidUserStatusTransitionException,
        NoClientManagerLeftException, PermanentIdMissmatchException {

    ExternalSystemConfiguration config = getConfiguration();
    // TODO can userId really be null? maybe in case of failed token auth?
    if (config == null || userIdentifier == null) {
        return e;
    }
    ExternalUserVO userVO = new ExternalUserVO();

    userVO.setExternalUserName(userIdentifier);
    userVO.setSystemId(config.getSystemId());
    boolean update = true;
    // handle the different exceptions by setting a new status
    // TODO UsernameNotFoundException should be handled here too, but is dangerous if we have
    // more than one external services and the 1st one does not contain the user
    if (e instanceof AccountExpiredException || e instanceof CredentialsExpiredException
            || e instanceof DisabledException || e instanceof LockedException) {
        userVO.setStatus(UserStatus.TEMPORARILY_DISABLED);
        e = new UserAccountTemporarilyDisabledException(e.getMessage());
        // } else if (e instanceof AuthenticationServiceException) {
        // TODO following correct
        // reactivate account to have normal login as fallback -- no, let communote manager
        // reactivate user account
        // userVO.setStatus(UserStatus.ACTIVE);
    } else if (e instanceof BadCredentialsException) {
        // typically thrown if the password was wrong, the cause might be that the password
        // was changed in the external repository. Theoretically we should call
        // AuthenticationManagement.onInvalidAuthentication if Authentication was a
        // UsernamePasswordAuthentication. But this is the wrong place because several
        // AuthenticationProviders will be called if available. Thus it is possible that some
        // providers fail and the last succeeds but login still fails because of the
        // onInvalidAuthentication logic. Therefore we throw a custom exception which holds the
        // details of the external system.
        e = new BadCredentialsForExternalSystemException(config.getSystemId(), e.getMessage(),
                e.getCause());
        update = false;
    } else {
        // do nothing
        update = false;
    }
    if (update) {
        UserManagement um = getUserManagement();
        um.updateExternalUser(userVO);
    }
    return e;
}
项目:incubator-taverna-server    文件:StrippedDownAuthProvider.java   
@PerfLogged
@Override
public Authentication authenticate(Authentication authentication)
        throws AuthenticationException {

    if (!(authentication instanceof UsernamePasswordAuthenticationToken))
        throw new IllegalArgumentException(
                "can only authenticate against username+password");
    UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication;

    // Determine username
    String username = (auth.getPrincipal() == null) ? "NONE_PROVIDED"
            : auth.getName();

    UserDetails user;

    try {
        user = retrieveUser(username, auth);
        if (user == null)
            throw new IllegalStateException(
                    "retrieveUser returned null - a violation of the interface contract");
    } catch (UsernameNotFoundException notFound) {
        if (logger.isDebugEnabled())
            logger.debug("User '" + username + "' not found", notFound);
        throw new BadCredentialsException("Bad credentials");
    }

    // Pre-auth
    if (!user.isAccountNonLocked())
        throw new LockedException("User account is locked");
    if (!user.isEnabled())
        throw new DisabledException("User account is disabled");
    if (!user.isAccountNonExpired())
        throw new AccountExpiredException("User account has expired");
    Object credentials = auth.getCredentials();
    if (credentials == null) {
        logger.debug("Authentication failed: no credentials provided");

        throw new BadCredentialsException("Bad credentials");
    }

    String providedPassword = credentials.toString();
    boolean matched = false;
    synchronized (authCache) {
        AuthCacheEntry pw = authCache.get(username);
        if (pw != null && providedPassword != null) {
            if (pw.valid(providedPassword))
                matched = true;
            else
                authCache.remove(username);
        }
    }
    // Auth
    if (!matched) {
        if (!passwordEncoder.matches(providedPassword, user.getPassword())) {
            logger.debug("Authentication failed: password does not match stored value");

            throw new BadCredentialsException("Bad credentials");
        }
        if (providedPassword != null)
            synchronized (authCache) {
                authCache.put(username, new AuthCacheEntry(providedPassword));
            }
    }

    // Post-auth
    if (!user.isCredentialsNonExpired())
        throw new CredentialsExpiredException(
                "User credentials have expired");

    return createSuccessAuthentication(user, auth, user);
}
项目:irplus    文件:UrLdapAuthenticationProvider.java   
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    Assert.isInstanceOf(LdapAuthenticationToken.class, authentication,
        messages.getMessage("AbstractUserDetailsAuthenticationProvider.onlySupports",
            "Only UsernamePasswordAuthenticationToken is supported"));

    LdapAuthenticationToken userToken = (LdapAuthenticationToken)authentication;

    String username = userToken.getName();


    if (!StringUtils.hasLength(username)) {
        throw new BadCredentialsException(messages.getMessage("LdapAuthenticationProvider.emptyUsername",
                "Empty Username"));
    }

    String password = (String) authentication.getCredentials();
    Assert.notNull(password, "Null password was supplied in authentication token");

    if (password.length() == 0) {
        log.debug("Rejecting empty password for user " + username);
        throw new BadCredentialsException(messages.getMessage("LdapAuthenticationProvider.emptyPassword",
                "Empty Password"));
    }

    try {

        // convert to username/password for bind
        DirContextOperations userData = getAuthenticator().authenticate(new UsernamePasswordAuthenticationToken(username, password));
        Collection<GrantedAuthority> extraAuthorities = loadUserAuthorities(userData, username, password);
        UserDetails user = userDetailsContextMapper.mapUserFromContext(userData, username, extraAuthorities);

        if( user != null )
        {
            if (!user.isAccountNonLocked()) {
                throw new LockedException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.locked",
                    "User account is locked"), user);
            }

            if (!user.isEnabled()) {
                throw new DisabledException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.disabled",
                    "User is disabled"), user);
            }

            if (!user.isAccountNonExpired()) {
                throw new AccountExpiredException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.expired",
                    "User account has expired"), user);
            }
        }

        log.debug("creating successful authentication");
        return createSuccessfulAuthentication(userToken, user);

    } catch (NamingException ldapAccessFailure) {
        throw new AuthenticationServiceException(ldapAccessFailure.getMessage(), ldapAccessFailure);
    }
    catch(UsernameNotFoundException usernameNotFoundException)
    {
        throw new BadCredentialsException(usernameNotFoundException.getMessage(), usernameNotFoundException);
    }
}