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.cloudfoundry.identity.uaa.password.PasswordChangeEndpoint.java

@ExceptionHandler
public View handleException(ScimResourceNotFoundException e) {
    // There's no point throwing BadCredentialsException here because it is
    // caught and
    // logged (then ignored) by the caller.
    return new ConvertingExceptionView(new ResponseEntity<ExceptionReport>(
            new ExceptionReport(new BadCredentialsException("Invalid password change request"), false),
            HttpStatus.UNAUTHORIZED), messageConverters);
}

From source file:org.cloudfoundry.identity.uaa.password.PasswordChangeEndpoint.java

@ExceptionHandler
public View handleException(ScimException e) {
    // No need to log the underlying exception (it will be logged by the
    // caller)/*from   w  w  w  .  jav a2  s. c  o  m*/
    return new ConvertingExceptionView(new ResponseEntity<ExceptionReport>(
            new ExceptionReport(new BadCredentialsException("Invalid password change request"), false),
            e.getStatus()), messageConverters);
}

From source file:org.cloudfoundry.identity.uaa.provider.oauth.XOAuthAuthenticationManager.java

@Override
protected UaaUser userAuthenticated(Authentication request, UaaUser userFromRequest, UaaUser userFromDb) {
    boolean userModified = false;
    boolean is_invitation_acceptance = isAcceptedInvitationAuthentication();
    String email = userFromRequest.getEmail();
    logger.debug("XOAUTH user authenticated:" + email);
    if (is_invitation_acceptance) {
        String invitedUserId = (String) RequestContextHolder.currentRequestAttributes().getAttribute("user_id",
                RequestAttributes.SCOPE_SESSION);
        logger.debug("XOAUTH user accepted invitation, user_id:" + invitedUserId);
        userFromDb = getUserDatabase().retrieveUserById(invitedUserId);
        if (email != null) {
            if (!email.equalsIgnoreCase(userFromDb.getEmail())) {
                throw new BadCredentialsException(
                        "OAuth User email mismatch. Authenticated email doesn't match invited email.");
            }//from   w ww  .  ja  v  a  2  s .  c o  m
        }
        publish(new InvitedUserAuthenticatedEvent(userFromDb));
        userFromDb = getUserDatabase().retrieveUserById(invitedUserId);
    }

    //we must check and see if the email address has changed between authentications
    if (request.getPrincipal() != null) {
        if (haveUserAttributesChanged(userFromDb, userFromRequest)) {
            logger.debug("User attributed have changed, updating them.");
            userFromDb = userFromDb.modifyAttributes(email, userFromRequest.getGivenName(),
                    userFromRequest.getFamilyName(), userFromRequest.getPhoneNumber())
                    .modifyUsername(userFromRequest.getUsername());
            userModified = true;
        }
    }
    ExternalGroupAuthorizationEvent event = new ExternalGroupAuthorizationEvent(userFromDb, userModified,
            userFromRequest.getAuthorities(), true);
    publish(event);
    return getUserDatabase().retrieveUserById(userFromDb.getId());
}

From source file:org.cloudfoundry.identity.uaa.provider.saml.LoginSamlAuthenticationProvider.java

protected UaaUser createIfMissing(UaaPrincipal samlPrincipal, boolean addNew,
        Collection<? extends GrantedAuthority> authorities, MultiValueMap<String, String> userAttributes) {
    UaaUser user = null;/*from w w  w . ja  v  a2 s  .co m*/
    String invitedUserId = null;
    boolean is_invitation_acceptance = isAcceptedInvitationAuthentication();
    if (is_invitation_acceptance) {
        invitedUserId = (String) RequestContextHolder.currentRequestAttributes().getAttribute("user_id",
                RequestAttributes.SCOPE_SESSION);
        user = userDatabase.retrieveUserById(invitedUserId);
        if (userAttributes.getFirst(EMAIL_ATTRIBUTE_NAME) != null) {
            if (!userAttributes.getFirst(EMAIL_ATTRIBUTE_NAME).equalsIgnoreCase(user.getEmail())) {
                throw new BadCredentialsException(
                        "SAML User email mismatch. Authenticated email doesn't match invited email.");
            }
        } else {
            userAttributes = new LinkedMultiValueMap<>(userAttributes);
            userAttributes.add(EMAIL_ATTRIBUTE_NAME, user.getEmail());
        }
        addNew = false;
        if (user.getUsername().equals(user.getEmail()) && !user.getUsername().equals(samlPrincipal.getName())) {
            user.setVerified(true);
            user = user.modifyUsername(samlPrincipal.getName());
        }
        publish(new InvitedUserAuthenticatedEvent(user));
        user = userDatabase.retrieveUserById(invitedUserId);
    }

    boolean userModified = false;
    UaaUser userWithSamlAttributes = getUser(samlPrincipal, userAttributes);
    try {
        if (user == null) {
            user = userDatabase.retrieveUserByName(samlPrincipal.getName(), samlPrincipal.getOrigin());
        }
    } catch (UsernameNotFoundException e) {
        UaaUser uaaUser = userDatabase.retrieveUserByEmail(userWithSamlAttributes.getEmail(),
                samlPrincipal.getOrigin());
        if (uaaUser != null) {
            user = uaaUser.modifyUsername(samlPrincipal.getName());
        } else {
            if (!addNew) {
                throw new LoginSAMLException("SAML user does not exist. "
                        + "You can correct this by creating a shadow user for the SAML user.", e);
            }
            // Register new users automatically
            publish(new NewUserAuthenticatedEvent(userWithSamlAttributes));
            try {
                user = userDatabase.retrieveUserByName(samlPrincipal.getName(), samlPrincipal.getOrigin());
            } catch (UsernameNotFoundException ex) {
                throw new BadCredentialsException(
                        "Unable to establish shadow user for SAML user:" + samlPrincipal.getName());
            }
        }
    }
    if (haveUserAttributesChanged(user, userWithSamlAttributes)) {
        userModified = true;
        user = user.modifyAttributes(userWithSamlAttributes.getEmail(), userWithSamlAttributes.getGivenName(),
                userWithSamlAttributes.getFamilyName(), userWithSamlAttributes.getPhoneNumber());
    }
    publish(new ExternalGroupAuthorizationEvent(user, userModified, authorities, true));
    user = userDatabase.retrieveUserById(user.getId());
    UaaPrincipal result = new UaaPrincipal(user);
    Authentication success = new UaaAuthentication(result, user.getAuthorities(), null);
    publish(new UserAuthenticationSuccessEvent(user, success));
    return user;
}

From source file:org.cloudfoundry.identity.uaa.provider.saml.LoginSamlAuthenticationProvider.java

protected UaaUser getUser(UaaPrincipal principal, MultiValueMap<String, String> userAttributes) {
    String name = principal.getName();
    String email = userAttributes.getFirst(EMAIL_ATTRIBUTE_NAME);
    String givenName = userAttributes.getFirst(GIVEN_NAME_ATTRIBUTE_NAME);
    String familyName = userAttributes.getFirst(FAMILY_NAME_ATTRIBUTE_NAME);
    String phoneNumber = userAttributes.getFirst(PHONE_NUMBER_ATTRIBUTE_NAME);
    String userId = OriginKeys.NotANumber;
    String origin = principal.getOrigin() != null ? principal.getOrigin() : OriginKeys.LOGIN_SERVER;
    String zoneId = principal.getZoneId();
    if (name == null && email != null) {
        name = email;/* w w w  .j a  va  2  s . co  m*/
    }
    if (name == null && OriginKeys.NotANumber.equals(userId)) {
        throw new BadCredentialsException("Cannot determine username from credentials supplied");
    } else if (name == null) {
        //we have user_id, name is irrelevant
        name = "unknown";
    }
    if (email == null) {
        if (name.contains("@")) {
            if (name.split("@").length == 2 && !name.startsWith("@") && !name.endsWith("@")) {
                email = name;
            } else {
                email = name.replaceAll("@", "") + "@unknown.org";
            }
        } else {
            email = name + "@unknown.org";
        }
    }
    if (givenName == null) {
        givenName = email.split("@")[0];
    }
    if (familyName == null) {
        familyName = email.split("@")[1];
    }
    return new UaaUser(new UaaUserPrototype().withEmail(email).withGivenName(givenName)
            .withFamilyName(familyName).withPhoneNumber(phoneNumber).withModified(new Date()).withId(userId)
            .withUsername(name).withPassword("").withAuthorities(Collections.EMPTY_LIST).withCreated(new Date())
            .withOrigin(origin).withExternalId(name).withVerified(true).withZoneId(zoneId).withSalt(null)
            .withPasswordLastModified(null));
}

From source file:org.cloudfoundry.identity.uaa.scim.dao.standard.JdbcScimUserProvisioning.java

private void checkPasswordMatches(String id, String oldPassword) {

    String currentPassword;//from   www .java 2  s  .  c o m
    try {
        currentPassword = jdbcTemplate.queryForObject(READ_PASSWORD_SQL, new Object[] { id },
                new int[] { Types.VARCHAR }, String.class);
    } catch (IncorrectResultSizeDataAccessException e) {
        throw new ScimResourceNotFoundException("User " + id + " does not exist");
    }

    if (!passwordEncoder.matches(oldPassword, currentPassword)) {
        throw new BadCredentialsException("Old password is incorrect");
    }
}

From source file:org.cloudfoundry.identity.uaa.scim.jdbc.JdbcScimUserProvisioning.java

@Override
public void changePassword(final String id, String oldPassword, final String newPassword)
        throws ScimResourceNotFoundException {
    if (oldPassword != null && !checkPasswordMatches(id, oldPassword)) {
        throw new BadCredentialsException("Old password is incorrect");
    }/*from ww  w  . ja va  2 s  .  c  o  m*/
    if (checkPasswordMatches(id, newPassword)) {
        return; //we don't want to update the same password
    }
    final String encNewPassword = passwordEncoder.encode(newPassword);
    final String zoneId = IdentityZoneHolder.get().getId();
    int updated = jdbcTemplate.update(CHANGE_PASSWORD_SQL, new PreparedStatementSetter() {
        @Override
        public void setValues(PreparedStatement ps) throws SQLException {
            Timestamp t = new Timestamp(System.currentTimeMillis());
            ps.setTimestamp(1, t);
            ps.setString(2, encNewPassword);
            ps.setTimestamp(3, getPasswordLastModifiedTimestamp(t));
            ps.setString(4, id);
            ps.setString(5, zoneId);
        }
    });
    if (updated == 0) {
        throw new ScimResourceNotFoundException("User " + id + " does not exist");
    }
    if (updated != 1) {
        throw new ScimResourceConstraintFailedException("User " + id + " duplicated");
    }
}

From source file:org.cloudfoundry.identity.uaa.scim.JdbcScimUserProvisioning.java

private void checkPasswordMatches(String id, String oldPassword) {
    String currentPassword;//from  w ww  . j a va 2s .  c  o  m
    try {
        currentPassword = jdbcTemplate.queryForObject(READ_PASSWORD_SQL, new Object[] { id },
                new int[] { Types.VARCHAR }, String.class);
    } catch (IncorrectResultSizeDataAccessException e) {
        throw new UserNotFoundException("User " + id + " does not exist");
    }

    if (!passwordEncoder.matches(oldPassword, currentPassword)) {
        throw new BadCredentialsException("Old password is incorrect");
    }
}

From source file:org.cloudifysource.security.CloudifyDaoAuthenticationProvider.java

@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
    Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication,
            messages.getMessage("AbstractUserDetailsAuthenticationProvider.onlySupports",
                    "Only UsernamePasswordAuthenticationToken is supported"));

    logger.finest("CloudifyDaoAuthenticationProvider: authenticate");
    final UsernamePasswordAuthenticationToken userToken = (UsernamePasswordAuthenticationToken) authentication;
    final CloudifyUserDetails user;

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

    if (StringUtils.isBlank(username)) {
        throw new IllegalArgumentException("Empty username not allowed");
    }//from w  ww  .j ava 2s.com
    Assert.notNull(password, "Null password was supplied in authentication token");
    logger.fine("Processing authentication request for user: " + username);

    // Get the Cloudify user details from the user details service
    try {
        user = retrieveUser(username);
        String retrievedUserPassword = user.getPassword();

        if (!password.equals(retrievedUserPassword)) {
            logger.warning("Authentication failed: password does not match stored value");
            throw new BadCredentialsException(messages
                    .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
        }
    } catch (final UsernameNotFoundException e) {
        logger.warning("User '" + username + "' not found");
        throw e;
    }

    // authenticate
    runAuthenticationChecks(user);

    // create a successful and full authentication token
    return createSuccessfulAuthentication(userToken, user);
}

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

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

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    String token = getParamFromRequest(httpRequest, tokenRequestParamKey);
    String tenantName = getParamFromRequest(httpRequest, tenantRequestParamKey);

    try {/*from ww  w  . j av a 2s.  co m*/
        // get encrypted token cookie with the user profile information
        String encryptedToken = getCipherTokenCookie(httpRequest);

        // get the cipher
        SimpleDesCipher cipher = new SimpleDesCipher(cipherkey);

        // try to use the encryptedToken first
        if (encryptedToken != null && !encryptedToken.isEmpty()) {

            // decrypt the cookie and read values from it
            String[] profileValues = getProfileValues(encryptedToken, cipher);

            String profileToken = profileValues[TOKEN];

            /*  Validate the token.  If the simple token & cookie token don't match,
             *  the user may have changed, so use the basic ticket in this case
             */
            if (profileToken.equals(token) && profile.validateUserToken(profileToken)) {

                authenticateWithCipherToken(chain, httpRequest, httpResponse, tenantName, cipher, profileValues,
                        profileToken);

            } else {

                // try authenticate with the simple token, is token in cipher is no longer valid
                authenticateWithSimpleToken(chain, httpRequest, httpResponse, token, tenantName, cipher);
            }

            /*  if no encrypted token, look for regular token & start with that
             *  this will always happen before the encrypted token
             */
        } else {

            authenticateWithSimpleToken(chain, httpRequest, httpResponse, token, tenantName, cipher);
        }

    } catch (org.craftercms.social.exceptions.AuthenticationException authExc) {
        failRequest(httpRequest, httpResponse, new BadCredentialsException(authExc.getMessage()));

    }
}