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:de.hybris.platform.acceleratorstorefrontcommons.security.AbstractAcceleratorAuthenticationProvider.java

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

    if (getBruteForceAttackCounter().isAttack(username)) {
        try {
            final UserModel userModel = getUserService().getUserForUID(StringUtils.lowerCase(username));
            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);
        }

        throw new BadCredentialsException(
                messages.getMessage("CoreAuthenticationProvider.badCredentials", "Bad credentials"));

    }

    return super.authenticate(authentication);

}

From source file:ru.ttk.baloo.rest.security.oauth.CustomUserAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    LOG.info("Going to process authentication: " + authentication);
    if (authentication != null && authentication.getPrincipal() != null
            && authentication.getCredentials() != null) {

        LOG.info("authentication principal: " + authentication.getPrincipal());
        LOG.info("authentication credentials: " + authentication.getCredentials());

        /*/*from ww w  .jav  a2 s. com*/
         * authentication.getPrincipal() <=> userName
         * authentication.getCredentials() <=> password
         */
        IRemoteUser remoteUser = remoteServiceFindUser.findUser(authentication.getPrincipal().toString(),
                authentication.getCredentials().toString());
        if (remoteUser != null) {
            List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
            CustomUserPasswordAuthenticationToken auth = new CustomUserPasswordAuthenticationToken(
                    authentication.getPrincipal(), authentication.getCredentials(), grantedAuthorities);
            return auth;
        }
    }
    throw new BadCredentialsException(WRONG_USER_CREDENTIALS);
}

From source file:com.formkiq.core.service.SpringSecurityService.java

/**
 * Check Request for Basic Authorization.
 * @param authorization {@link String}//from   w  ww.  ja  va 2 s  .  c  o  m
 * @return clientid {@link String}
 */
public String checkBasicAuthorization(final String authorization) {

    String value = authorization;

    if (!StringUtils.isEmpty(value)) {

        value = value.replaceAll("Basic ", "");
        String[] args = Strings.decode(value, ":");
        String clientid = args[0];
        String clientSecret = args[1];

        if (this.oauthservice.isValidClient(clientid, clientSecret)) {
            return clientid;
        }
    }

    throw new BadCredentialsException("User does not have access to Client");
}

From source file:com.katropine.oauth.CustomUserAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    LOGGER.warning("!!!Authenticate: " + authentication.getPrincipal().toString() + ":"
            + authentication.getCredentials().toString());

    if (!supports(authentication.getClass())) {
        return null;
    }/*from   w  w w  .j  a  v  a 2 s  . c o  m*/
    if (authentication.getCredentials() == null) {
        LOGGER.warning("No credentials found in request.");
        boolean throwExceptionWhenTokenRejected = false;
        if (throwExceptionWhenTokenRejected) {
            throw new BadCredentialsException("No pre-authenticated credentials found in request.");
        }
        return null;
    }

    User user = userDAO.getByEmail(authentication.getPrincipal().toString());

    BCryptPasswordEncoder enc = new BCryptPasswordEncoder();
    if (!enc.matches(authentication.getCredentials().toString(), user.getPassword())) {
        throw new BadCredentialsException("Bad User Credentials.");
    }

    List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
    CustomUserPasswordAuthenticationToken auth = new CustomUserPasswordAuthenticationToken(
            authentication.getPrincipal(), authentication.getCredentials(), grantedAuthorities);

    return auth;

}

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

@Override
public DirContextOperations authenticate(Authentication authentication) {
    DirContextOperations user = null;//from w  w w  .j ava2 s .  c  o  m
    Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication,
            "Can only process UsernamePasswordAuthenticationToken objects");

    String username = authentication.getName();
    String password = (String) authentication.getCredentials();

    if (StringUtils.isEmpty(password)) {
        LOG.debug("Rejecting empty password for user " + username);
        throw new BadCredentialsException(
                messages.getMessage("BindAuthenticator.emptyPassword", "Empty Password"));
    }

    // If DN patterns are configured, try authenticating with them directly
    for (String dn : getUserDns(username)) {
        user = bindWithDn(dn, username, password);

        if (user != null) {
            break;
        }
    }

    // Otherwise use the configured search object to find the user and authenticate with the returned DN.
    if (user == null && getUserSearch() != null) {
        DirContextOperations userFromSearch = getUserSearch().searchForUser(username);
        user = bindWithDn(userFromSearch.getDn().toString(), username, password);
    }

    try {
        if (user != null && StringUtils.isNotEmpty(gizmoGroup)) {
            BaseLdapPathContextSource ctxSource = (BaseLdapPathContextSource) getContextSource();
            DirContext ctx = ctxSource.getReadOnlyContext();

            DistinguishedName userDn = new DistinguishedName(user.getDn());
            userDn.prepend(ctxSource.getBaseLdapPath());

            SearchControls controls = new SearchControls();
            controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            String filter = String.format(GROUP_SEARCH_QUERY, gizmoGroup, userDn.toCompactString());
            NamingEnumeration en = ctx.search("", filter, controls);
            if (!en.hasMore()) {
                throw new BadCredentialsException(
                        messages.getMessage("BindAuthenticator.badCredentials", "Bad credentials"));
            }
        }
    } catch (javax.naming.NamingException ex) {
        throw new BadCredentialsException("Couldn't check group membership");
    }

    if (user == null) {
        throw new BadCredentialsException(
                messages.getMessage("BindAuthenticator.badCredentials", "Bad credentials"));
    }

    return user;
}

From source file:cn.net.withub.demo.bootsec.hello.security.CustomAuthenticationProvider.java

@Transactional
@Override//from   w ww .j a v  a  2s  .c  o  m
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
    String username = token.getName(); //???
    //?
    UserDetails userDetails = null;
    if (username != null) {
        userDetails = userDetailsService.loadUserByUsername(username);
    }

    if (userDetails == null) {
        return null;//null??
        //throw new UsernameNotFoundException("??/?");
    } else if (!userDetails.isEnabled()) {
        throw new DisabledException("?");
    } else if (!userDetails.isAccountNonExpired()) {
        throw new AccountExpiredException("?");
    } else if (!userDetails.isAccountNonLocked()) {
        throw new LockedException("??");
    } else if (!userDetails.isCredentialsNonExpired()) {
        throw new LockedException("?");
    }

    //??
    String encPass = userDetails.getPassword();

    //authentication?credentials
    if (!md5PasswordEncoder.isPasswordValid(encPass, token.getCredentials().toString(), null)) {
        throw new BadCredentialsException("Invalid username/password");
    }

    //?
    return new UsernamePasswordAuthenticationToken(userDetails, encPass, userDetails.getAuthorities());
}

From source file:com.autoupdater.server.utils.authentication.BCryptAuthenticationManager.java

/**
 * Authenticate user./*from  w ww . j  a v a  2  s.co  m*/
 * 
 * @param auth
 *            authentication data passed by Spring Security
 * @return result of authentication
 */
@Override
public Authentication authenticate(Authentication auth) throws AuthenticationException {
    logger.debug("Performing authentication");

    User user = null;

    logger.debug("Searching user [" + auth.getName() + "] in DB");
    try {
        user = userService.findByUsername(auth.getName());
    } catch (Exception e) {
        logger.error("User [" + auth.getName() + "] does not exists (exception)!");
        throw new AuthenticationServiceException("Error while obtaining User data!");
    }
    if (user == null) {
        logger.error("User [" + auth.getName() + "] does not exists (null)!");
        throw new BadCredentialsException("User does not exists!");
    }

    if (!BCrypt.checkpw(auth.getCredentials().toString(), user.getHashedPassword())) {
        logger.error("Password doesn't match!");
        throw new BadCredentialsException("Password doesn't match!");
    }

    logger.debug("User details are good and ready to go");
    return new UsernamePasswordAuthenticationToken(auth.getName(), auth.getCredentials(),
            getAuthorities(user.isAdmin(), user.isPackageAdmin()));
}

From source file:br.com.joaops.smt.security.SmtAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication a) throws AuthenticationException {
    String username = a.getName();
    String password = a.getCredentials().toString();

    UserDetails user = this.userDetails.loadUserByUsername(username);

    if (user == null) {
        String message = this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials",
                "AbstractUserDetailsAuthenticationProvider.badCredentials");
        throw new BadCredentialsException(message);
    }//from   ww  w  . j  av a  2  s.  com

    if (!user.getUsername().equals(username)) {
        String message = this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials",
                "AbstractUserDetailsAuthenticationProvider.badCredentials");
        throw new BadCredentialsException(message);
    }

    if (!passwordEncoder.matches(password, user.getPassword())) {
        String message = this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials",
                "AbstractUserDetailsAuthenticationProvider.badCredentials");
        throw new BadCredentialsException(message);
    }

    if (user.isEnabled() == false) {
        String message = this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.disabled",
                "AbstractUserDetailsAuthenticationProvider.disabled");
        throw new DisabledException(message);
    }

    if (user.isAccountNonLocked() == false) {
        String message = this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.locked",
                "AbstractUserDetailsAuthenticationProvider.locked");
        throw new LockedException(message);
    }

    if (user.isAccountNonExpired() == false) {
        String message = this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.expired",
                "AbstractUserDetailsAuthenticationProvider.expired");
        throw new AccountExpiredException(message);
    }

    if (user.isCredentialsNonExpired() == false) {
        String message = this.messages.getMessage(
                "AbstractUserDetailsAuthenticationProvider.credentialsExpired",
                "AbstractUserDetailsAuthenticationProvider.credentialsExpired");
        throw new CredentialsExpiredException(message);
    }

    return new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities());
}

From source file:com.ar.dev.tierra.api.config.security.CustomAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication auth) throws AuthenticationException {
    String username = String.valueOf(auth.getName());
    String password = String.valueOf(auth.getCredentials().toString());

    Usuarios us = null;/*  w  ww.  j a  v  a2  s  .  co  m*/
    boolean success = false;
    try {
        us = user.findUsuarioByUsername(username);
        success = passwordEncoder.matches(password, us.getPassword());
    } catch (Exception ex) {
    }
    if (success == true) {
        final List<GrantedAuthority> grantedAuths = new ArrayList<>();
        String authority;
        switch (us.getRoles().getNombreRol()) {
        case "ADMINISTRADOR":
            authority = "ROLE_ADMIN";
            break;
        case "VENDEDOR":
            authority = "ROLE_VENDEDOR";
            break;
        default:
            authority = "ROLE_NONE";
            break;
        }
        GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(authority);
        grantedAuths.add(grantedAuthority);
        final UserDetails principal = new User(username, password, grantedAuths);
        final Authentication authentication = new UsernamePasswordAuthenticationToken(principal, password,
                grantedAuths);
        us = null;
        return authentication;
    } else {
        throw new BadCredentialsException("Bad Credentials");
    }
}

From source file:de.kaiserpfalzEdv.office.ui.web.security.KPOfficeAuthenticationProvider.java

@Override
protected void additionalAuthenticationChecks(UserDetails userDetails,
        UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
    if (KPOfficeUserDetail.class.isAssignableFrom(userDetails.getClass())) {
        try {//from w  w  w. j  a v  a  2s.  c om
            service.check(((KPOfficeUserDetail) userDetails).getTicket());

            LOG.info("Checked: {}", userDetails);
        } catch (NoSuchTicketException | InvalidTicketException e) {
            throw new BadCredentialsException("Wrong credentials for '" + userDetails.getUsername() + "'.");
        }
    }
}