Package org.springframework.security.authentication

Examples of org.springframework.security.authentication.BadCredentialsException


  }

  @Test
  public void testCommenceWithHtmlAndJsonAccept() throws Exception {
    request.addHeader("Accept", String.format("%s,%s", MediaType.TEXT_HTML_VALUE, MediaType.APPLICATION_JSON));
    entryPoint.commence(request, response, new BadCredentialsException("Bad"));
    assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatus());
    assertEquals(null, response.getErrorMessage());
  }
View Full Code Here


        }
      }
      return infos;
    }
    else {
      throw new BadCredentialsException("Bad credentials: not a username/password authentication.");
    }
  }
View Full Code Here

            throws AuthenticationException {

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

        if (StringUtils.isBlank(username) || StringUtils.isBlank(clearPassword)) {
            throw new BadCredentialsException(
                    "Username and password can not be empty");
        }

        String encodedPassword = passwordEncoderService.encodePassword(
                clearPassword, username);
        User user = getUserFromDB(username);

        // If user != null then exists in LibrePlan
        if (null != user && user.isLibrePlanUser()) {
            // is a LibrePlan user, then we must authenticate against DB
            return authenticateInDatabase(username, user, encodedPassword);
        }

        // If it's a LDAP or null user, then we must authenticate against LDAP
        // Load LDAPConfiguration properties
        configuration = loadLDAPConfiguration();

        if (configuration.getLdapAuthEnabled()) {
            // Sets the new context to ldapTemplate
            ldapTemplate.setContextSource(loadLDAPContext());

            try {
                // Test authentication for user against LDAP
                if (authenticateAgainstLDAP(username, clearPassword)) {
                    // Authentication against LDAP was ok
                    if (null == user) {
                        // User does not exist in LibrePlan must be imported
                        user = createLDAPUserWithRoles(username, encodedPassword);
                    } else {
                        // Update password
                        if (configuration.isLdapSavePasswordsDB()) {
                            user.setPassword(encodedPassword);
                        }
                        // Update roles from LDAP
                        setRoles(user);
                    }
                    saveUserOnTransaction(user);
                    return loadUserDetails(username);
                } else {
                    throw new BadCredentialsException("User is not in LDAP.");
                }
            } catch (Exception e) {
                // This exception captures when LDAP authentication is not
                // possible
                LOG.info(
View Full Code Here

            String encodedPassword) {
        if (null != user && null != user.getPassword()
                && encodedPassword.equals(user.getPassword())) {
            return loadUserDetails(username);
        } else {
            throw new BadCredentialsException(
                    "Credentials are not the same as in database.");
        }
    }
View Full Code Here

      throws AuthenticationException {
    User gnDetails = (User) userDetails;
       
    if (authentication.getCredentials() == null) {
      Log.warning(Log.JEEVES, "Authentication failed: no credentials provided");
      throw new BadCredentialsException("Authentication failed: no credentials provided");
    }

    if (!encoder.matches(authentication.getCredentials().toString(), gnDetails.getPassword())) {
      Log.warning(Log.JEEVES, "Authentication failed: wrong password provided");
      throw new BadCredentialsException("Authentication failed: wrong password provided");
    }
  }
View Full Code Here

    Object salt = null;
    if (this.saltSource != null) {
      salt = this.saltSource.getSalt(userDetails);
    }
    if (authentication.getCredentials() == null) {
      throw new BadCredentialsException(messages.getMessage("CustomAuthenticationProvider.badCredentials", "Bad credentials"), includeDetailsObject ? userDetails : null);
    }
    String presentedPassword = authentication.getCredentials().toString();
    if (!passwordEncoder.isPasswordValid(userDetails.getPassword(), presentedPassword, salt)) {
      throw new BadCredentialsException(messages.getMessage("CustomAuthenticationProvider.badCredentials", "Bad credentials"), includeDetailsObject ? userDetails : null);
    }
    String company = ((AuthenticationToken) authentication).getCompany().toString();
    if (company == null || company.equals(""))
      throw new BadCredentialsException(messages.getMessage("CustomAuthenticationProvider.badCredentials", "Bad credentials"), includeDetailsObject ? userDetails : null);

  }
View Full Code Here

      if (authentication.getPrincipal().equals("lurker")) {
        grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_LURKER"));
      }
      return new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), grantedAuthorities);
    } else {
      throw new BadCredentialsException("Authentication failed");
    }
  }
View Full Code Here

                    logger.debug("extracted username: '" + username + "'; realm: '" + username + "'; nonce: '"
                            + username + "'; uri: '" + username + "'; response: '" + username + "'");
                }

                fail(request, response,
                        new BadCredentialsException(messages.getMessage("DigestAuthenticationFilter.missingMandatory",
                                new Object[]{section212response}, "Missing mandatory digest value; received header {0}")));

                return;
            }

            // Check all required parameters for an "auth" qop were supplied (ie RFC 2617)
            if ("auth".equals(qop)) {
                if ((nc == null) || (cnonce == null)) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("extracted nc: '" + nc + "'; cnonce: '" + cnonce + "'");
                    }

                    fail(request, response,
                            new BadCredentialsException(messages.getMessage("DigestAuthenticationFilter.missingAuth",
                                    new Object[]{section212response}, "Missing mandatory digest value; received header {0}")));

                    return;
                }
            }

            // Check realm name equals what we expected
            if (!this.getAuthenticationEntryPoint().getRealmName().equals(realm)) {
                fail(request, response,
                        new BadCredentialsException(messages.getMessage("DigestAuthenticationFilter.incorrectRealm",
                                new Object[]{realm, this.getAuthenticationEntryPoint().getRealmName()},
                                "Response realm name '{0}' does not match system realm name of '{1}'")));

                return;
            }

            // Check nonce was a Base64 encoded (as sent by DigestAuthenticationEntryPoint)
            if (!Base64.isBase64(nonce.getBytes())) {
                fail(request, response,
                        new BadCredentialsException(messages.getMessage("DigestAuthenticationFilter.nonceEncoding",
                                new Object[]{nonce}, "Nonce is not encoded in Base64; received nonce {0}")));

                return;
            }

            // Decode nonce from Base64
            // format of nonce is:
            //   base64(expirationTime + ":" + md5Hex(expirationTime + ":" + key))
            String nonceAsPlainText = new String(Base64.decode(nonce.getBytes()));
            String[] nonceTokens = StringUtils.delimitedListToStringArray(nonceAsPlainText, ":");

            if (nonceTokens.length != 2) {
                fail(request, response,
                        new BadCredentialsException(messages.getMessage("DigestAuthenticationFilter.nonceNotTwoTokens",
                                new Object[]{nonceAsPlainText}, "Nonce should have yielded two tokens but was {0}")));

                return;
            }

            // Extract expiry time from nonce
            long nonceExpiryTime;

            try {
                nonceExpiryTime = new Long(nonceTokens[0]).longValue();
            } catch (NumberFormatException nfe) {
                fail(request, response,
                        new BadCredentialsException(messages.getMessage("DigestAuthenticationFilter.nonceNotNumeric",
                                new Object[]{nonceAsPlainText},
                                "Nonce token should have yielded a numeric first token, but was {0}")));

                return;
            }

            // Check signature of nonce matches this expiry time
            String expectedNonceSignature = DigestAuthUtils.md5Hex(nonceExpiryTime + ":"
                    + this.getAuthenticationEntryPoint().getKey());

            if (!expectedNonceSignature.equals(nonceTokens[1])) {
                fail(request, response,
                        new BadCredentialsException(messages.getMessage("DigestAuthenticationFilter.nonceCompromised",
                                new Object[]{nonceAsPlainText}, "Nonce token compromised {0}")));

                return;
            }

            // Lookup password for presented username
            // NB: DAO-provided password MUST be clear text - not encoded/salted
            // (unless this instance's passwordAlreadyEncoded property is 'false')
            boolean loadedFromDao = false;
            UserDetails user = userCache.getUserFromCache(username);

            if (user == null) {
                loadedFromDao = true;

                try {
                    user = userDetailsService.loadUserByUsername(username);
                } catch (UsernameNotFoundException notFound) {
                    fail(request, response,
                            new BadCredentialsException(messages.getMessage("DigestAuthenticationFilter.usernameNotFound",
                                    new Object[]{username}, "Username {0} not found")));

                    return;
                }

                if (user == null) {
                    throw new AuthenticationServiceException(
                            "AuthenticationDao returned null, which is an interface contract violation");
                }

                userCache.putUserInCache(user);
            }

            // Compute the expected response-digest (will be in hex form)
            String serverDigestMd5;

            // Don't catch IllegalArgumentException (already checked validity)
            serverDigestMd5 = DigestAuthUtils.generateDigest(passwordAlreadyEncoded, username, realm, user.getPassword(),
                    request.getMethod(), uri, qop, nonce, nc, cnonce);

            // If digest is incorrect, try refreshing from backend and recomputing
            if (!serverDigestMd5.equals(responseDigest) && !loadedFromDao) {
                if (logger.isDebugEnabled()) {
                    logger.debug(
                            "Digest comparison failure; trying to refresh user from DAO in case password had changed");
                }

                try {
                    user = userDetailsService.loadUserByUsername(username);
                } catch (UsernameNotFoundException notFound) {
                    // Would very rarely happen, as user existed earlier
                    fail(request, response,
                            new BadCredentialsException(messages.getMessage("DigestAuthenticationFilter.usernameNotFound",
                                    new Object[]{username}, "Username {0} not found")));
                }

                userCache.putUserInCache(user);

                // Don't catch IllegalArgumentException (already checked validity)
                serverDigestMd5 = DigestAuthUtils.generateDigest(passwordAlreadyEncoded, username, realm, user.getPassword(),
                        request.getMethod(), uri, qop, nonce, nc, cnonce);
            }

            // If digest is still incorrect, definitely reject authentication attempt
            if (!serverDigestMd5.equals(responseDigest)) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Expected response: '" + serverDigestMd5 + "' but received: '" + responseDigest
                            + "'; is AuthenticationDao returning clear text passwords?");
                }

                fail(request, response,
                        new BadCredentialsException(messages.getMessage("DigestAuthenticationFilter.incorrectResponse",
                                "Incorrect response")));
                return;
            }

            // To get this far, the digest must have been valid
View Full Code Here

        if (authentication.getPrincipal() == null) {
            logger.debug("No pre-authenticated principal found in request.");

            if (throwExceptionWhenTokenRejected) {
                throw new BadCredentialsException("No pre-authenticated principal found in request.");
            }
            return null;
        }

        if (authentication.getCredentials() == null) {
            logger.debug("No pre-authenticated credentials found in request.");

            if (throwExceptionWhenTokenRejected) {
                throw new BadCredentialsException("No pre-authenticated credentials found in request.");
            }
            return null;
        }

        UserDetails ud = preAuthenticatedUserDetailsService.loadUserDetails(authentication);
View Full Code Here

            } else if (status == OpenIDAuthenticationStatus.CANCELLED) {
                throw new AuthenticationCancelledException("Log in cancelled");
            } else if (status == OpenIDAuthenticationStatus.ERROR) {
                throw new AuthenticationServiceException("Error message from server: " + response.getMessage());
            } else if (status == OpenIDAuthenticationStatus.FAILURE) {
                throw new BadCredentialsException("Log in failed - identity could not be verified");
            } else if (status == OpenIDAuthenticationStatus.SETUP_NEEDED) {
                throw new AuthenticationServiceException(
                        "The server responded setup was needed, which shouldn't happen");
            } else {
                throw new AuthenticationServiceException("Unrecognized return value " + status.toString());
View Full Code Here

TOP

Related Classes of org.springframework.security.authentication.BadCredentialsException

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.