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:com.epam.storefront.security.AcceleratorAuthenticationProvider.java

@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
    final String username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED"
            : authentication.getName();//from   w  ww.j a v a 2 s .c om

    if (getBruteForceAttackCounter().isAttack(username)) {
        try {
            final UserModel userModel = getUserService().getUserForUID(StringUtils.lowerCase(username));

            if (userModel instanceof CustomerModel) {
                final CustomerModel customerModel = (CustomerModel) userModel;

                customerModel.setLoginDisabled(true);
                customerModel.setStatus(Boolean.TRUE);
                customerModel.setAttemptCount(Integer.valueOf(0));

                getModelService().save(customerModel);
            } else {
                userModel.setLoginDisabled(true);
                getModelService().save(userModel);
            }

            bruteForceAttackCounter.resetUserCounter(userModel.getUid());
        } catch (final UnknownIdentifierException e) {
            LOG.warn("Brute force attack attempt for non existing user name " + username);
        } finally {
            throw new BadCredentialsException(
                    messages.getMessage("CoreAuthenticationProvider.badCredentials", "Bad credentials"));
        }
    }

    return doAuth(authentication, username);
}

From source file:io.github.autsia.crowly.security.CrowlyAuthenticationManager.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    try {/*from   w  ww.j  a va  2 s .c  o m*/
        CrowlyUser dbUser = userRepository.findByEmail(authentication.getName());
        if (bCryptPasswordEncoder.matches(authentication.getCredentials().toString(), dbUser.getPassword())) {
            return new UsernamePasswordAuthenticationToken(authentication.getName(),
                    authentication.getCredentials(), getAuthorities(dbUser));
        }
    } catch (Exception e) {
        logger.error(e.getMessage());
    }
    throw new BadCredentialsException(authentication.getName());
}

From source file:io.gravitee.management.idp.memory.authentication.InMemoryAuthentificationProvider.java

@Override
protected void additionalAuthenticationChecks(UserDetails userDetails,
        UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
    if (authentication.getCredentials() == null) {
        LOGGER.debug("Authentication failed: no credentials provided");
        throw new BadCredentialsException(messages
                .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
    }/*from   w w  w  . j a  va  2 s.  c om*/

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

    if (!passwordEncoder.matches(presentedPassword, userDetails.getPassword())) {
        LOGGER.debug("Authentication failed: password does not match stored value");
        throw new BadCredentialsException(messages
                .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
    }
}

From source file:org.awesomeagile.testing.hackpad.FakeHackpadController.java

@RequestMapping(value = "/api/1.0/pad/{padId}/content", method = RequestMethod.POST, consumes = MediaType.TEXT_HTML_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody/*  w  w w .  ja  v  a  2s .  co  m*/
public HackpadStatus updateHackpad(@PathVariable("padId") String padId, @RequestBody String content,
        @RequestParam("oauth_consumer_key") String key) {
    if (!clientId.equals(key)) {
        throw new BadCredentialsException("Invalid client ID: " + key);
    }
    PadIdentity padIdentity = new PadIdentity(padId);
    if (!hackpads.containsKey(padIdentity)) {
        return new HackpadStatus(false);
    }
    hackpads.put(padIdentity, content);
    return new HackpadStatus(true);
}

From source file:sk.lazyman.gizmo.security.GizmoAuthProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String principal = (String) authentication.getPrincipal();
    if (StringUtils.isBlank(principal)) {
        throw new BadCredentialsException("web.security.provider.invalid");
    }/*from w  w w  . j av a  2s . com*/

    if (useLdapAuth()) {
        return authenticateUsingLdap(authentication);
    }

    return authenticateUsingDb(authentication);
}

From source file:net.seedboxer.web.security.AuthenticationAPIKeyFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    @SuppressWarnings("unchecked")
    Map<String, String[]> parms = request.getParameterMap();

    if (parms.containsKey(APIKEY_PARAM)) {
        String apikey = parms.get(APIKEY_PARAM)[0];

        if (Token.validate(apikey)) {
            try {

                UserDetails userDetails = seedboxerUDS.loadUserByAPIKey(apikey);
                Authentication authentication = createSuccessfulAuthentication(request, userDetails);
                SecurityContextHolder.getContext().setAuthentication(authentication);

            } catch (UsernameNotFoundException notFound) {
                fail(request, response,/*  w w w .ja v a 2s.  c  o m*/
                        new BadCredentialsException(
                                messages.getMessage("DigestAuthenticationFilter.usernameNotFound",
                                        new Object[] { apikey }, "User with APIKey {0} not found")));

                return;
            }
        } else {
            fail(request, response,
                    new BadCredentialsException(
                            messages.getMessage("DigestAuthenticationFilter.usernameNotFound",
                                    new Object[] { apikey }, "Invalid APIKey {0}")));

            return;
        }
    }
    chain.doFilter(request, response);
}

From source file:com.amediamanager.service.UserServiceImpl.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication;
    String username = String.valueOf(auth.getPrincipal());
    String password = String.valueOf(auth.getCredentials());

    User user = find(username);/*from w  ww. ja v a  2 s .co m*/

    if (null == user || (!BCrypt.checkpw(password, user.getPassword()))) {
        throw new BadCredentialsException("Invalid username or password");
    }

    List<GrantedAuthority> grantedAuths = new ArrayList<GrantedAuthority>();
    grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));

    // Create new auth token
    auth = new UsernamePasswordAuthenticationToken(username, null, grantedAuths);
    auth.setDetails(user);
    return auth;
}

From source file:org.carewebframework.vista.security.base.BaseAuthenticationProvider.java

@SuppressWarnings("deprecation")
private void checkAuthResult(AuthResult result, IUser user) throws AuthenticationException {
    switch (result.status) {
    case SUCCESS:
        return;/*from  www  . j  a v  a 2s . com*/

    case CANCELED:
        throw new AuthenticationCancelledException(
                StringUtils.defaultIfEmpty(result.reason, "Authentication attempt was cancelled."));

    case EXPIRED:
        throw new CredentialsExpiredException(
                StringUtils.defaultIfEmpty(result.reason, "Your password has expired."), user);

    case FAILURE:
        throw new BadCredentialsException(
                StringUtils.defaultIfEmpty(result.reason, "Your username or password was not recognized."));

    case LOCKED:
        throw new LockedException(StringUtils.defaultIfEmpty(result.reason,
                "Your user account has been locked and cannot be accessed."));

    case NOLOGINS:
        throw new DisabledException(
                StringUtils.defaultIfEmpty(result.reason, "Logins are currently disabled."));
    }
}

From source file:fr.xebia.springframework.security.core.providers.ExtendedDaoAuthenticationProvider.java

/**
 * Checks that the {@link org.springframework.security.web.authentication.WebAuthenticationDetails#getRemoteAddress()}
 * matches one of the {@link ExtendedUser#getAllowedRemoteAddresses()}. If
 * the given <code>userDetails</code> is not an {@link ExtendedUser} of if
 * the given <code>authentication.details</code> is not a
 * {@link org.springframework.security.web.authentication.WebAuthenticationDetails}, then the ip address check is silently
 * by passed.//www . j  a  v a  2s  .c om
 */
@Override
protected void additionalAuthenticationChecks(UserDetails userDetails,
        UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {

    super.additionalAuthenticationChecks(userDetails, authentication);

    if (!(userDetails instanceof ExtendedUser)) {
        if (log.isDebugEnabled()) {
            log.debug("Given userDetails '" + userDetails
                    + "' is not an ExtendedUser, skip ipAddress verification");
        }
        return;
    }
    ExtendedUser extendedUser = (ExtendedUser) userDetails;

    if (!(authentication.getDetails() instanceof WebAuthenticationDetails)) {
        if (log.isDebugEnabled()) {
            log.debug("Given authentication '" + authentication
                    + "' does not hold WebAuthenticationDetails, skip ipAddress verification");
        }
        return;
    }
    WebAuthenticationDetails webAuthenticationDetails = (WebAuthenticationDetails) authentication.getDetails();

    String remoteIpAddress = webAuthenticationDetails.getRemoteAddress();

    if (log.isDebugEnabled()) {
        log.debug("Evaluate permission for '" + extendedUser + "' to authenticate from ip address "
                + remoteIpAddress);
    }

    List<Pattern> allowedRemoteAddressesPatterns = extendedUser.getAllowedRemoteAddressesPatterns();
    if (!matchesOneAddress(remoteIpAddress, allowedRemoteAddressesPatterns)) {
        throw new BadCredentialsException("Access denied from IP : " + remoteIpAddress);
    }
}