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.dspace.EDMExport.service.EDMExportAuthenticationManager.java

/**
 * Redefinimos el mtodo para autenticarse
 * /*from   w w w. ja v  a 2s .com*/
 * @param auth objeto de Spring de Authentication {@link Authentication}
 * @return UsernamePasswordAuthenticationToken {@link Authentication}
 * @throws AuthenticationException
 */
@Override
public Authentication authenticate(Authentication auth) throws AuthenticationException {
    logger.debug("Performing EDMExport authentication");

    try {
        // Buscar usuario con login y grupo o slo con login
        if (groupIDStr != null && !groupIDStr.isEmpty()) {
            eperson = daoEperson.getEperson(auth.getName(), Integer.parseInt(groupIDStr));
        } else
            eperson = daoEperson.getEperson(auth.getName());
    } catch (Exception e) {
        logger.error("User " + auth.getName() + " does not exists! " + e.getMessage() + "," + e.toString(), e);
        //SecurityContextHolder.getContext().setAuthentication(null);
        throw new BadCredentialsException("User does not exists!");
    }

    // Validamos el password
    if (!passwordEncoder.isPasswordValid(eperson.getPassword(), (String) auth.getCredentials(), null)) {
        logger.error("Wrong password!" + eperson.getPassword() + " " + (String) auth.getCredentials());
        throw new BadCredentialsException("Wrong password!");
    }

    // Comprobamos que el login no se igual que el password, poco seguridad
    if (auth.getName().equals(auth.getCredentials())) {
        logger.debug("Entered username and password are the same!");
        throw new BadCredentialsException("Entered username and password are the same!");
    } else {
        logger.debug("User details are good and ready to go");
        return new UsernamePasswordAuthenticationToken(auth.getName(), auth.getCredentials(),
                getAuthorities(eperson.getAccess()));
    }
}

From source file:de.hybris.platform.acceleratorstorefrontcommons.security.AbstractAcceleratorAuthenticationProvider.java

/**
 * @see de.hybris.platform.spring.security.CoreAuthenticationProvider#additionalAuthenticationChecks(org.springframework.security.core.userdetails.UserDetails,
 *      org.springframework.security.authentication.AbstractAuthenticationToken)
 *///from w  w w.j  a  v  a 2s .  c  om
@Override
protected void additionalAuthenticationChecks(final UserDetails details,
        final AbstractAuthenticationToken authentication) throws AuthenticationException {
    super.additionalAuthenticationChecks(details, authentication);

    // Check if user has supplied no password
    if (StringUtils.isEmpty((String) authentication.getCredentials())) {
        throw new BadCredentialsException("Login without password");
    }
}

From source file:org.osiam.auth.login.ldap.OsiamLdapAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) {
    Preconditions.checkArgument(authentication instanceof OsiamLdapAuthentication,
            "OsiamLdapAuthenticationProvider only supports OsiamLdapAuthentication.");

    final OsiamLdapAuthentication userToken = (OsiamLdapAuthentication) authentication;

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

    if (Strings.isNullOrEmpty(username)) {
        throw new BadCredentialsException("OsiamLdapAuthenticationProvider: Empty Username");
    }//from   w  w w  .ja  v a 2s.c  o  m

    if (Strings.isNullOrEmpty(password)) {
        throw new BadCredentialsException("OsiamLdapAuthenticationProvider: Empty Password");
    }

    User user = resourceServerConnector.getUserByUsername(username);
    checkIfInternalUserExists(user);

    DirContextOperations userData = doAuthentication(userToken);

    UserDetails ldapUser = osiamLdapUserContextMapper.mapUserFromContext(userData, authentication.getName(),
            loadUserAuthorities(userData, authentication.getName(), (String) authentication.getCredentials()));

    user = synchronizeLdapData(userData, user);

    User authUser = new User.Builder(username).setId(user.getId()).build();

    List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();

    for (Role role : user.getRoles()) {
        grantedAuthorities.add(new SimpleGrantedAuthority(role.getValue()));
    }

    UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(authUser, null,
            grantedAuthorities);
    result.setDetails(authentication.getDetails());

    return result;
}

From source file:com.devicehive.auth.rest.providers.BasicAuthenticationProvider.java

@SuppressWarnings("unchecked")
@Override//from   ww w .  j  a  va 2s .c  om
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String key = (String) authentication.getPrincipal();
    String pass = (String) authentication.getCredentials();
    logger.debug("Basic authentication requested for username {}", key);

    UserVO user = null;
    try {
        user = userService.authenticate(key, pass);
    } catch (HiveException e) {
        logger.error("User auth failed", e);
    }
    if (user != null && user.getStatus() == UserStatus.ACTIVE) {
        String role = user.isAdmin() ? HiveRoles.ADMIN : HiveRoles.CLIENT;
        logger.info("User {} authenticated with role {}", key, role);

        HivePrincipal principal = new HivePrincipal(user);

        if (user.isAdmin()) {
            Set<String> allActions = AvailableActions.getAllActions();
            Set<HiveAction> allowedActions = new HashSet<>();
            allActions.forEach(action -> allowedActions.add(HiveAction.fromString(action)));
            principal.setActions(allowedActions);
        } else {
            String[] actions = AvailableActions.getClientActions();
            Set<HiveAction> allowedActions = new HashSet<>();
            for (String action : actions)
                allowedActions.add(HiveAction.fromString(action));
            principal.setActions(allowedActions);
        }

        return new HiveAuthentication(principal, AuthorityUtils.createAuthorityList(role));

    }
    logger.warn("Basic auth for {} failed", key);
    throw new BadCredentialsException("Invalid credentials");
}

From source file:org.carewebframework.security.spring.AbstractAuthenticationProvider.java

/**
 * Authentication Provider. Produces a trusted <code>UsernamePasswordAuthenticationToken</code>
 * if/*from ww  w .ja v a 2s.c  o  m*/
 * 
 * @param authentication The authentication context.
 * @return authentication Authentication object if authentication succeeded. Null if not.
 */
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    CWFAuthenticationDetails details = (CWFAuthenticationDetails) authentication.getDetails();
    String username = (String) authentication.getPrincipal();
    String password = (String) authentication.getCredentials();
    String domain = null;

    if (log.isDebugEnabled()) {
        log.debug("User: " + username);
        log.debug("Details, RA: " + details == null ? "null" : details.getRemoteAddress());
    }

    if (username != null) {
        String pcs[] = username.split("\\\\", 2);
        domain = pcs[0];
        username = pcs.length > 1 ? pcs[1] : null;
    }

    ISecurityDomain securityDomain = domain == null ? null
            : SecurityUtil.getSecurityService().getSecurityDomain(domain);

    if (username == null || password == null || securityDomain == null) {
        throw new BadCredentialsException("Missing security credentials.");
    }

    IUser user = authenticate(username, password, securityDomain, details);
    details.setDetail("user", user);
    List<GrantedAuthority> userAuthorities = new ArrayList<GrantedAuthority>();
    List<String> list = getAuthorities(user);
    Set<String> authorities = list == null ? new HashSet<String>() : new HashSet<String>(list);

    for (String grantedAuthority : grantedAuthorities) {
        if (grantedAuthority.startsWith("-")) {
            authorities.remove(grantedAuthority.substring(1));
        } else {
            authorities.add(grantedAuthority);
        }
    }

    for (String authority : authorities) {
        if (!authority.isEmpty()) {
            userAuthorities.add(new SimpleGrantedAuthority(authority));
        }
    }

    User principal = new User(username, password, true, true, true, true, userAuthorities);

    authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(),
            principal.getAuthorities());
    ((UsernamePasswordAuthenticationToken) authentication).setDetails(details);
    return authentication;
}

From source file:com.exxonmobile.ace.hybris.storefront.security.AcceleratorAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    final String username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED"
            : authentication.getName();//from  ww  w .  ja  v  a  2s.c o m
    if (getBruteForceAttackCounter().isAttack(username)) {
        try {
            UserModel userModel = getUserService().getUserForUID(StringUtils.lowerCase(username));
            userModel.setLoginDisabled(true);
            getModelService().save(userModel);
            bruteForceAttackCounter.resetUserCounter(userModel.getUid());
        } catch (UnknownIdentifierException e) {
            LOG.warn("Brute force attack attempt for non existing user name " + username);
        } finally {
            throw new BadCredentialsException(
                    messages.getMessage("CoreAuthenticationProvider.badCredentials", "Bad credentials"));
        }
    }

    // check if the user of the cart matches the current user and if the
    // user is not anonymous. If otherwise, remove delete the session cart as it might
    // be stolen / from another user
    String sessionCartUserId = getCartService().getSessionCart().getUser().getUid();

    if (!username.equals(sessionCartUserId)
            && !sessionCartUserId.equals(userService.getAnonymousUser().getUid())) {
        getCartService().setSessionCart(null);
    }
    return super.authenticate(authentication);
}

From source file:org.jasig.schedassist.web.security.CustomLDAPAuthenticationProvider.java

/**
 * Incorporates some of the //from   ww w. j a  v  a2s  .c  om
 *  (non-Javadoc)
 * @see org.springframework.security.authentication.dao.DaoAuthenticationProvider#additionalAuthenticationChecks(org.springframework.security.core.userdetails.UserDetails, org.springframework.security.authentication.UsernamePasswordAuthenticationToken)
 */
@Override
protected void additionalAuthenticationChecks(UserDetails userDetails,
        UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
    String username = authentication.getName();
    String password = (String) authentication.getCredentials();

    if (logger.isDebugEnabled()) {
        logger.debug("Processing authentication request for user: " + username);
    }

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

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

    try {
        DirContextOperations userData = getAuthenticator().authenticate(authentication);
        if (userData == null) {
            throw new BadCredentialsException(
                    messages.getMessage("LdapAuthenticationProvider.badCredentials", "Bad credentials"));
        }
    } catch (PasswordPolicyException ppe) {
        // The only reason a ppolicy exception can occur during a bind is that the account is locked.
        throw new LockedException(
                messages.getMessage(ppe.getStatus().getErrorCode(), ppe.getStatus().getDefaultMessage()));
    } catch (UsernameNotFoundException notFound) {
        if (hideUserNotFoundExceptions) {
            throw new BadCredentialsException(
                    messages.getMessage("LdapAuthenticationProvider.badCredentials", "Bad credentials"));
        } else {
            throw notFound;
        }
    }
}

From source file:org.dspace.rest.authentication.DSpaceAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Context context = null;/*from   w  ww  .  ja  va2s. c  om*/

    try {
        context = new Context();
        String name = authentication.getName();
        String password = authentication.getCredentials().toString();
        HttpServletRequest httpServletRequest = new DSpace().getRequestService().getCurrentRequest()
                .getHttpServletRequest();
        List<SimpleGrantedAuthority> grantedAuthorities = new ArrayList<>();

        int implicitStatus = authenticationService.authenticateImplicit(context, null, null, null,
                httpServletRequest);

        if (implicitStatus == AuthenticationMethod.SUCCESS) {
            log.info(LogManager.getHeader(context, "login", "type=implicit"));
            addSpecialGroupsToGrantedAuthorityList(context, httpServletRequest, grantedAuthorities);
            return createAuthenticationToken(password, context, grantedAuthorities);

        } else {
            int authenticateResult = authenticationService.authenticate(context, name, password, null,
                    httpServletRequest);
            if (AuthenticationMethod.SUCCESS == authenticateResult) {
                addSpecialGroupsToGrantedAuthorityList(context, httpServletRequest, grantedAuthorities);

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

                return createAuthenticationToken(password, context, grantedAuthorities);

            } else {
                log.info(LogManager.getHeader(context, "failed_login",
                        "email=" + name + ", result=" + authenticateResult));
                throw new BadCredentialsException("Login failed");
            }
        }
    } catch (BadCredentialsException e) {
        throw e;
    } catch (Exception e) {
        log.error("Error while authenticating in the rest api", e);
    } finally {
        if (context != null && context.isValid()) {
            try {
                context.complete();
            } catch (SQLException e) {
                log.error(e.getMessage() + " occurred while trying to close", e);
            }
        }
    }

    return null;
}

From source file:com.rockagen.gnext.service.spring.security.extension.BasicUrlAuthenticationFailureHandler.java

/**
 * handle locked ?//from  w  ww.  j  a v  a2  s .  c  o  m
 * 
 * @param userId
 * @return
 */
protected AuthenticationException handlerLocked(String userId) {

    AuthUser user = authUserServ.load(userId);
    if (user.getErrorCount() >= 5) {

        Long dateTime = user.getStateTime().getTime();
        // 1 DAY = 86 400 000 ms
        if (new Date().getTime() - dateTime < 86400000) {
            // Locked user if input 6 error password  
            user.setEnabled(0);
            authUserServ.add(user);
            return new DisabledException(messages.getMessage("AccountStatusUserDetailsChecker.locked"));
        }
    } else {
        // error count ++
        user.setErrorCount(user.getErrorCount() + 1);
        // state time
        user.setStateTime(new Date());
    }
    int onlyCount = 6 - user.getErrorCount();
    authUserServ.add(user);
    return new BadCredentialsException(
            messages.getMessage("AccountStatusUserDetailsChecker.onlyCount", new Object[] { onlyCount }));
}