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.uni_koeln.spinfo.maalr.mongo.SpringBackend.java

private String getUserLogin() {
    try {/*w  ww.  ja v a 2 s. c o m*/
        MaalrUserInfo user = userInfos.getOrCreateCurrentUser();
        return user.getLogin();
    } catch (Exception e) {
        throw new BadCredentialsException("Failed to get user login");
    }
}

From source file:es.osoco.grails.plugins.otp.authentication.OneTimePasswordAuthenticationProvider.java

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

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

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

    boolean cacheWasUsed = true;
    UserDetails user = getUserCache().getUserFromCache(username);

    if (user == null) {
        cacheWasUsed = false;/*from   w  ww.j  av a 2s  . com*/

        try {
            user = retrieveUser(username, (OneTimePasswordAuthenticationToken) authentication);
        } catch (UsernameNotFoundException notFound) {

            if (hideUserNotFoundExceptions) {
                throw new BadCredentialsException(messages.getMessage(
                        "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
            }
            throw notFound;
        }

        Assert.notNull(user, "retrieveUser returned null - a violation of the interface contract");
    }

    try {
        getPreAuthenticationChecks().check(user);
        additionalAuthenticationChecks(user, (OneTimePasswordAuthenticationToken) authentication);
    } catch (AuthenticationException exception) {
        if (cacheWasUsed) {
            // There was a problem, so try again after checking
            // we're using latest data (i.e. not from the cache)
            cacheWasUsed = false;
            user = retrieveUser(username, (OneTimePasswordAuthenticationToken) authentication);
            getPreAuthenticationChecks().check(user);
            additionalAuthenticationChecks(user, (OneTimePasswordAuthenticationToken) authentication);
        } else {
            throw exception;
        }
    }

    getPostAuthenticationChecks().check(user);

    if (!cacheWasUsed) {
        getUserCache().putUserInCache(user);
    }

    Object principalToReturn = user;

    if (isForcePrincipalAsString()) {
        principalToReturn = user.getUsername();
    }

    return createSuccessAuthentication(principalToReturn, authentication, user);
}

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

/**
 * Create a new {@link org.springframework.security.core.userdetails.UserDetails} by uid
 *
 * @param uid         uid/*from  w w w. j a  va  2 s  .c o  m*/
 * @param credentials Credentials(always was password)
 * @return {@link org.springframework.security.core.userdetails.UserDetails}
 * @throws org.springframework.security.authentication.BadCredentialsException if credentials invalid
 */
private UserDetails loadUser(String uid, String credentials) {

    // Not empty
    if (CommUtil.isBlank(uid) || CommUtil.isBlank(credentials)) {
        throw new BadCredentialsException(messages
                .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
    }

    // Load user
    Optional<AuthUser> u = authUserServ.load(uid);

    if (u.filter(x -> x.enabled()).isPresent()) {
        AuthUser user = u.get();
        // Check credentials
        checkCredentials(user.getPassword(), credentials, user.getSalt());

        // After authenticated handler
        afterAuthenticatedHandler(user);

        List<GrantedAuthority> authorities = new LinkedList<>();
        Set<AuthGroup> groups = user.getGroups();
        if (groups != null && groups.size() > 0) {
            groups.forEach(x -> x.getRoles()
                    .forEach(y -> authorities.add(new SimpleGrantedAuthority(y.getName().trim()))));
        }
        return new User(user.getUid(), user.getPassword(), true, true, true, true, authorities);

    } else {
        throw new UsernameNotFoundException(
                messages.getMessage("", new Object[] { uid }, "User {0} has no GrantedAuthority"));
    }

}

From source file:com.cruz.sec.config.MyAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    System.out.println("Entrando a la verificacin del usuario");
    System.out.println("Nombre de usuario: " + authentication.getName());
    UserDetails userDetails = (UserDetails) this.customJDBCDaoImpl.loadUserByUsername(authentication.getName());
    if (userDetails.isEnabled()) {
        Object salt = null;/*from  ww  w.  ja v  a2 s  .  c  om*/
        if (this.saltSource != null) {
            salt = saltSource.getSalt(userDetails);
        }
        if (shaPasswordEncoder.isPasswordValid(userDetails.getPassword(),
                authentication.getCredentials().toString(), salt)) {
            //Verifico si el usuario ya tiene una sesin abierta, si es as la cierro y le creo su nueva instancia
            verifUserInSession(userDetails.getUsername());
            return new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        }
        throw new BadCredentialsException("Bad credentials");
    } else {
        throw new DisabledException("User disabled");
    }
}

From source file:com.evolveum.midpoint.web.security.MidPointAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (StringUtils.isBlank((String) authentication.getPrincipal())) {
        throw new BadCredentialsException("web.security.provider.invalid");
    }//from  ww w.  j a va  2 s .c  om

    MidPointPrincipal principal = null;
    try {
        principal = userProfileService.getPrincipal((String) authentication.getPrincipal());
    } catch (ObjectNotFoundException ex) {
        LOGGER.debug("Authentication of user with username '{}' failed: not found: {}", ex.getMessage(), ex);
        throw new BadCredentialsException("web.security.provider.access.denied");
    } catch (Exception ex) {
        LOGGER.error("Can't get user with username '{}'. Unknown error occured, reason {}.",
                new Object[] { authentication.getPrincipal(), ex.getMessage(), ex });
        throw new AuthenticationServiceException("web.security.provider.unavailable");
    }

    Authentication token = null;
    try {
        token = authenticateUser(principal, authentication);
    } catch (BadCredentialsException ex) {
        LOGGER.debug("Authentication of user with username '{}' failed: bad credentials: {}", ex.getMessage(),
                ex);
        throw ex;
    } catch (Exception ex) {
        LOGGER.error("Can't authenticate user '{}': {}",
                new Object[] { authentication.getPrincipal(), ex.getMessage(), ex });
        throw new AuthenticationServiceException("web.security.provider.unavailable");
    }

    LOGGER.debug("User '{}' authenticated ({}), authorities: {}", new Object[] { authentication.getPrincipal(),
            authentication.getClass().getSimpleName(), principal.getAuthorities() });
    return token;
}

From source file:eu.cloud4soa.frontend.commons.server.security.C4sAuthenticationProvider.java

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

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

    UserInstance userInstance;/*from  w ww . ja v  a 2s . co  m*/

    try {
        userInstance = userService.authenticateUser(username, password);
    } catch (Throwable e) {
        if (e.getMessage().contains("wrong username") || e.getMessage().contains("No user instance"))
            throw new BadCredentialsException("Bad username or password.");

        String msg = "An error occurred while authenticating user '" + Strings.defaultString(username) + "': "
                + e.getMessage();
        logger.debug(msg, e);
        throw new BadCredentialsException(msg, e);
    }

    Authentication auth = new C4sUserAuthentication(loadUserByUsername(username).getAuthorities(),
            authentication, userInstance.getUriId());
    auth.setAuthenticated(true);

    return auth;
}

From source file:cz.lbenda.coursing.server.security.SecurityServiceImpl.java

@Override
public final void changePassword(User user, char[] oldPassword, char[] newPassword)
        throws BadCredentialsException {
    if (user == null) {
        throw new NullPointerException("The user object mustn't be null");
    }//from  w w w  . j ava  2 s. c o  m
    if (((user.getPasswd() == null || user.getPasswd().length() == 0)
            && (oldPassword == null || oldPassword.length == 0))
            || passwordEncoder.matches(String.valueOf(oldPassword), user.getPasswd())) {
        user.setPasswd(passwordEncoder.encode(String.valueOf(newPassword)));
    } else {
        throw new BadCredentialsException("The old password didn't match to user password.");
    }
}

From source file:com.github.djabry.platform.service.security.DefaultAuthenticationProvider.java

/**
 * Performs authentication with the same contract as {@link
 * org.springframework.security.authentication.AuthenticationManager#authenticate(org.springframework.security.core.Authentication)}.
 *
 * @param authentication the authentication request object.
 * @return a fully authenticated object including credentials. May return <code>null</code> if the
 * <code>AuthenticationProvider</code> is unable to support authentication of the passed
 * <code>Authentication</code> object. In such a case, the next <code>AuthenticationProvider</code> that
 * supports the presented <code>Authentication</code> class will be tried.
 * @throws org.springframework.security.core.AuthenticationException if authentication fails.
 *///  w  ww. j  a  v  a  2s.  c o m
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String username = authentication.getName();
    String password = authentication.getCredentials().toString();

    UserDetails details = userDetailsService.loadUserByUsername(username);
    SecurityToken<DBUser> token = springAuthenticationService.login(username, password);

    if (token != null) {
        return new UsernamePasswordAuthenticationToken(username, password, details.getAuthorities());
    }

    throw new BadCredentialsException("Incorrect credentials");

}

From source file:fr.gael.dhus.spring.security.authentication.DefaultAuthenticationProvider.java

@Override
@Transactional(propagation = Propagation.REQUIRED)
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String username = (String) authentication.getPrincipal();
    String password = (String) authentication.getCredentials();
    String ip = "unknown";
    if (authentication.getDetails() instanceof WebAuthenticationDetails) {
        ip = ((WebAuthenticationDetails) authentication.getDetails()).getRemoteAddress();
    }/*ww w  .ja  va  2  s  . c o  m*/
    LOGGER.info("Connection attempted by '" + authentication.getName() + "' from " + ip);
    arwDao.loginStart(username);

    User user = userService.getUserNoCheck(username);
    if (user == null || user.isDeleted()) {
        throw new BadCredentialsException(errorMessage);
    }

    PasswordEncryption encryption = user.getPasswordEncryption();
    if (!encryption.equals(PasswordEncryption.NONE)) {
        MessageDigest md;
        try {
            md = MessageDigest.getInstance(encryption.getAlgorithmKey());
            password = new String(Hex.encode(md.digest(password.getBytes("UTF-8"))));
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            arwDao.loginEnd(user, false);
            throw new BadCredentialsException("Authentication process failed", e);
        }
    }

    if (!user.getPassword().equals(password)) {
        LOGGER.warn(new Message(MessageType.USER, "Connection refused for '" + username + "' from " + ip
                + " : error in login/password combination"));
        arwDao.loginEnd(user, false);
        throw new BadCredentialsException(errorMessage);
    }

    for (AccessRestriction restriction : user.getRestrictions()) {
        LOGGER.warn("Connection refused for '" + username + "' from " + ip + " : account is locked ("
                + restriction.getBlockingReason() + ")");
        arwDao.loginEnd(user, false);
        throw new LockedException(restriction.getBlockingReason());
    }

    LOGGER.info("Connection success for '" + username + "' from " + ip);
    arwDao.loginEnd(user, true);
    return new ValidityAuthentication(user, user.getAuthorities());
}

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

@Override
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication)
        throws AuthenticationException {
    KPOfficeUserDetail result;/*from ww w .  java 2  s  . c  o  m*/

    try {
        OfficeLoginTicket ticket = service.login(username, (String) authentication.getCredentials());

        result = new KPOfficeUserDetail(ticket);
    } catch (InvalidLoginException e) {
        throw new UsernameNotFoundException("Username '" + username + "' not found.");
    } catch (NoSuchAccountException e) {
        throw new BadCredentialsException("Wrong password for '" + username + "'.");
    }

    LOG.info("Created: {}", result);
    return result;
}