Example usage for org.springframework.security.authentication BadCredentialsException BadCredentialsException

List of usage examples for org.springframework.security.authentication BadCredentialsException BadCredentialsException

Introduction

In this page you can find the example usage for org.springframework.security.authentication BadCredentialsException BadCredentialsException.

Prototype

public BadCredentialsException(String msg) 

Source Link

Document

Constructs a BadCredentialsException with the specified message.

Usage

From source file:org.craftercms.social.util.support.security.CrafterProfileFilter.java

/**
 *
 * @param chain//from   w  ww. j  a va  2  s  . c  o  m
 * @param httpRequest
 * @param httpResponse
 * @param token
 * @param tenantName
 * @param cipher
 * @throws IOException
 * @throws ServletException
 * @throws org.craftercms.social.exceptions.AuthenticationException
 */
private void authenticateWithSimpleToken(FilterChain chain, HttpServletRequest httpRequest,
        HttpServletResponse httpResponse, String token, String tenantName, SimpleDesCipher cipher)
        throws IOException, ServletException, org.craftercms.social.exceptions.AuthenticationException {

    if (token != null && !token.isEmpty()) {
        if (profile.validateUserToken(token)) {

            final Profile userProfile = profile.getUserInformation(token);

            // validate tenant, exception thrown for failure
            validateTenant(httpRequest.getServerName(), tenantName, userProfile.getTenantName(),
                    userProfile.getId());

            SecurityContextHolder.getContext().setAuthentication(getCrafterAuthToken(userProfile));

            // generate the encrypted token and set in response
            httpResponse.addCookie(getCipherCookie(cipher, token, userProfile));

            chain.doFilter(httpRequest, httpResponse);

        } else {
            profile.resetAppToken();
            failRequest(httpRequest, httpResponse, new BadCredentialsException("Token is no longer valid"));
        }

    } else if (token.isEmpty()) { // ANONYMOUS support
        SecurityContextHolder.getContext().setAuthentication(getCrafterAuthAnonymousToken());
        chain.doFilter(httpRequest, httpResponse);
    } else {

        failRequest(httpRequest, httpResponse,
                new AuthenticationCredentialsNotFoundException("Need param is not on the request"));
    }
}

From source file:org.dspace.app.rest.security.EPersonRestAuthenticationProvider.java

private Authentication authenticateNewLogin(Authentication authentication) {
    Context newContext = null;//w  w w.j a  va  2s .  c o  m
    Authentication output = null;

    if (authentication != null) {
        try {
            newContext = new Context();
            String name = authentication.getName();
            String password = Objects.toString(authentication.getCredentials(), null);

            int implicitStatus = authenticationService.authenticateImplicit(newContext, null, null, null,
                    request);

            if (implicitStatus == AuthenticationMethod.SUCCESS) {
                log.info(LogManager.getHeader(newContext, "login", "type=implicit"));
                output = createAuthentication(password, newContext);
            } else {
                int authenticateResult = authenticationService.authenticate(newContext, name, password, null,
                        request);
                if (AuthenticationMethod.SUCCESS == authenticateResult) {

                    log.info(LogManager.getHeader(newContext, "login", "type=explicit"));

                    output = createAuthentication(password, newContext);
                } else {
                    log.info(LogManager.getHeader(newContext, "failed_login",
                            "email=" + name + ", result=" + authenticateResult));
                    throw new BadCredentialsException("Login failed");
                }
            }
        } finally {
            if (newContext != null && newContext.isValid()) {
                try {
                    newContext.complete();
                } catch (SQLException e) {
                    log.error(e.getMessage() + " occurred while trying to close", e);
                }
            }
        }
    }

    return output;
}

From source file:org.dspace.app.rest.security.EPersonRestAuthenticationProvider.java

private Authentication createAuthentication(final String password, final Context context) {
    EPerson ePerson = context.getCurrentUser();

    if (ePerson != null && StringUtils.isNotBlank(ePerson.getEmail())) {
        //Pass the eperson ID to the request service
        requestService.setCurrentUserId(ePerson.getID());

        return new DSpaceAuthentication(ePerson, getGrantedAuthorities(context, ePerson));

    } else {//from ww  w .  j av a  2  s  .c om
        log.info(LogManager.getHeader(context, "failed_login",
                "No eperson with an non-blank e-mail address found"));
        throw new BadCredentialsException("Login failed");
    }
}

From source file:org.egov.infra.config.security.authentication.provider.ApplicationAuthenticationProvider.java

private void lockAccount(Authentication authentication) {
    Optional<LoginAttempt> loginAttempt = loginAttemptService.updateFailedAttempt(authentication.getName());
    if (loginAttempt.isPresent()) {
        if (loginAttempt.get().getFailedAttempts() == MAX_LOGIN_ATTEMPT_ALLOWED) {
            throw new LockedException(messages.getMessage(ACCOUNT_LOCKED_MSG_KEY, ACCOUNT_LOCKED_DEFAULT_MSG));
        } else if (loginAttempt.get().getFailedAttempts() > 2) {
            throw new BadCredentialsException(format(TOO_MANY_ATTEMPTS_MSG_FORMAT,
                    MAX_LOGIN_ATTEMPT_ALLOWED - loginAttempt.get().getFailedAttempts()));
        }/*from w  ww .  j a  v a 2 s . c  om*/
    }
}

From source file:org.egov.infra.config.security.authentication.provider.ApplicationAuthenticationProvider.java

@Override
protected void additionalAuthenticationChecks(UserDetails userDetails,
        UsernamePasswordAuthenticationToken authentication) {
    HashMap<String, String> authenticationCredentials = (HashMap<String, String>) authentication
            .getCredentials();//from   ww  w  .  jav  a 2s  .c om
    if (authenticationCredentials == null || !passwordEncoder
            .matches(authenticationCredentials.get(LOGIN_PASS_FIELD), userDetails.getPassword())) {
        throw new BadCredentialsException(messages.getMessage(BAD_CRED_MSG_KEY, BAD_CRED_DEFAULT_MSG));
    }
}

From source file:org.encuestame.core.security.SocialAccountAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (authentication instanceof SocialAuthenticationToken) {
        SocialAuthenticationToken response = (SocialAuthenticationToken) authentication;
        // handle the various possibilities
        // Lookup user details
        UserDetails userDetails;// w  w  w . ja  v a  2  s  .  c  o  m
        try {
            userDetails = socialUserService.loadAccountConnection(response.getProfileId(),
                    response.getProvider());
            //logger.debug("user details "+userDetails);
        } catch (EnMeNoSuchAccountConnectionException e) {
            throw new BadCredentialsException(e.getMessage());
        }
        Authentication auth = createSuccessAuthentication(response);
        return auth;
    } else {
        return null;
    }
}

From source file:org.encuestame.core.security.web.EnMeUsernameProvider.java

@Override
protected void additionalAuthenticationChecks(UserDetails userDetails,
        final UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {

    Object salt = null;/* ww  w . ja  v a 2  s .  c  om*/

    if (this.saltSource != null) {
        salt = this.saltSource.getSalt(userDetails);
    }

    final EnMeUserAccount detailsDataAccount = (EnMeUserAccount) userDetails;

    if (log.isDebugEnabled()) {
        log.debug("detailsDataAccount " + detailsDataAccount.toString());
    }

    if (!detailsDataAccount.isSocialCredentials()) {
        log.debug("SOCIAL CREDENTIALS OFF");
        if (authentication.getCredentials() == null) {
            logger.debug("Authentication failed: no credentials provided");
            throw new BadCredentialsException(messages
                    .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
        }

        String presentedPassword = authentication.getCredentials().toString();

        if (!passwordEncoder.isPasswordValid(userDetails.getPassword(), presentedPassword, salt)) {
            logger.debug("Authentication failed: password does not match stored value");
            throw new BadCredentialsException(messages
                    .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
        }
    } else {
        if (log.isInfoEnabled()) {
            log.info("SOCIAL CREDENTIALS ON");
        }
    }
}

From source file:org.encuestame.core.security.web.SocialAccountAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (authentication instanceof SocialAuthenticationToken) {
        SocialAuthenticationToken response = (SocialAuthenticationToken) authentication;
        // handle the various possibilities
        // Lookup user details
        UserDetails userDetails;/*from w  w  w  . j a v a 2  s .  c o m*/
        try {
            userDetails = socialUserService.loadAccountConnection(response.getProfileId(),
                    response.getProvider());
            logger.debug("user details :: " + userDetails);
        } catch (EnMeNoSuchAccountConnectionException e) {
            throw new BadCredentialsException(e.getMessage());
        }
        Authentication auth = createSuccessAuthentication(response);
        return auth;
    } else {
        return null;
    }
}

From source file:org.fao.geonet.kernel.security.ecas.ECasAuthenticationProvider.java

public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (!supports(authentication.getClass())) {
        return null;
    }/*  w  w  w. ja v a  2 s .co m*/

    if (authentication instanceof UsernamePasswordAuthenticationToken
            && (!CasAuthenticationFilter.CAS_STATEFUL_IDENTIFIER
                    .equals(authentication.getPrincipal().toString())
                    && !CasAuthenticationFilter.CAS_STATELESS_IDENTIFIER
                            .equals(authentication.getPrincipal().toString()))) {
        // UsernamePasswordAuthenticationToken not CAS related
        return null;
    }

    // If an existing CasAuthenticationToken, just check we created it
    if (authentication instanceof CasAuthenticationToken) {
        if (this.key.hashCode() == ((CasAuthenticationToken) authentication).getKeyHash()) {
            return authentication;
        } else {
            throw new BadCredentialsException(messages.getMessage("CasAuthenticationProvider.incorrectKey",
                    "The presented CasAuthenticationToken does not contain the expected key"));
        }
    }

    // Ensure credentials are presented
    if ((authentication.getCredentials() == null) || "".equals(authentication.getCredentials())) {
        throw new BadCredentialsException(messages.getMessage("CasAuthenticationProvider.noServiceTicket",
                "Failed to provide a CAS service ticket to validate"));
    }

    boolean stateless = false;

    if (authentication instanceof UsernamePasswordAuthenticationToken
            && CasAuthenticationFilter.CAS_STATELESS_IDENTIFIER.equals(authentication.getPrincipal())) {
        stateless = true;
    }

    CasAuthenticationToken result = null;

    if (stateless) {
        // Try to obtain from cache
        result = statelessTicketCache.getByTicketId(authentication.getCredentials().toString());
    }

    if (result == null) {
        result = this.authenticateNow(authentication);
        result.setDetails(authentication.getDetails());
    }

    if (stateless) {
        // Add to cache
        statelessTicketCache.putTicketInCache(result);
    }

    return result;
}

From source file:org.fao.geonet.kernel.security.ecas.ECasUserDetailAuthenticationProvider.java

@Override
protected void additionalAuthenticationChecks(UserDetails userDetails,
        UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
    User gnDetails = userRepo.findOneByUsername(userDetails.getUsername());
    if (authentication.getCredentials() == null) {
        logger.error("Authentication failed: no credentials provided");
        throw new BadCredentialsException("Authentication failed: no credentials provided");
    }/*w w  w.j av a 2 s . com*/
    if (!encoder.matches(authentication.getCredentials().toString(), gnDetails.getPassword())) {
        logger.warn("Authentication failed: wrong password provided");
        throw new BadCredentialsException("Authentication failed: wrong password provided");
    }
}