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.springframework.security.ui.ntlm.NtlmAuthenticationFilter.java

/**
 * Checks the user credentials against the domain controller.
 *
 * @param session the <code>HTTPSession</code> object.
 * @param dcAddress the domain controller address.
 * @param auth the <code>NtlmPasswordAuthentication</code> object.
 * @throws IOException//w  w w. j a v a  2  s  . c  o m
 */
private void logon(final HttpSession session, final UniAddress dcAddress, final NtlmPasswordAuthentication auth)
        throws IOException {
    try {
        SmbSession.logon(dcAddress, auth);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(auth + " successfully authenticated against " + dcAddress);
        }
    } catch (SmbAuthException e) {
        LOGGER.error("Credentials " + auth + " were not accepted by the domain controller " + dcAddress);

        if (retryOnAuthFailure) {
            LOGGER.debug("Restarting NTLM authentication handshake");
            session.setAttribute(STATE_ATTR, BEGIN);
            throw new NtlmBeginHandshakeException();
        }

        throw new BadCredentialsException("Bad NTLM credentials");
    } finally {
        session.removeAttribute(CHALLENGE_ATTR);
    }
}

From source file:org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider.java

/**
 * Authenticate the given PreAuthenticatedAuthenticationToken.
 * <p>//ww  w  . ja v  a2 s.  c om
 * If the principal contained in the authentication object is null, the request will
 * be ignored to allow other providers to authenticate it.
 */
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (!supports(authentication.getClass())) {
        return null;
    }

    if (logger.isDebugEnabled()) {
        logger.debug("PreAuthenticated authentication request: " + authentication);
    }

    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((PreAuthenticatedAuthenticationToken) authentication);

    userDetailsChecker.check(ud);

    PreAuthenticatedAuthenticationToken result = new PreAuthenticatedAuthenticationToken(ud,
            authentication.getCredentials(), ud.getAuthorities());
    result.setDetails(authentication.getDetails());

    return result;
}

From source file:org.springframework.security.web.authentication.preauth.x509.SubjectDnX509PrincipalExtractor.java

public Object extractPrincipal(X509Certificate clientCert) {
    // String subjectDN = clientCert.getSubjectX500Principal().getName();
    String subjectDN = clientCert.getSubjectDN().getName();

    logger.debug("Subject DN is '" + subjectDN + "'");

    Matcher matcher = subjectDnPattern.matcher(subjectDN);

    if (!matcher.find()) {
        throw new BadCredentialsException(messages.getMessage("SubjectDnX509PrincipalExtractor.noMatching",
                new Object[] { subjectDN }, "No matching pattern was found in subject DN: {0}"));
    }/* ww w.ja v  a2s  .  c o  m*/

    if (matcher.groupCount() != 1) {
        throw new IllegalArgumentException("Regular expression must contain a single group ");
    }

    String username = matcher.group(1);

    logger.debug("Extracted Principal name is '" + username + "'");

    return username;
}

From source file:org.springframework.security.web.authentication.www.BasicAuthenticationFilterTests.java

@Before
public void setUp() throws Exception {
    SecurityContextHolder.clearContext();
    UsernamePasswordAuthenticationToken rodRequest = new UsernamePasswordAuthenticationToken("rod", "koala");
    rodRequest.setDetails(new WebAuthenticationDetails(new MockHttpServletRequest()));
    Authentication rod = new UsernamePasswordAuthenticationToken("rod", "koala",
            AuthorityUtils.createAuthorityList("ROLE_1"));

    manager = mock(AuthenticationManager.class);
    when(manager.authenticate(rodRequest)).thenReturn(rod);
    when(manager.authenticate(not(eq(rodRequest)))).thenThrow(new BadCredentialsException(""));

    filter = new BasicAuthenticationFilter(manager, new BasicAuthenticationEntryPoint());
}

From source file:org.springframework.security.web.authentication.www.DigestAuthenticationFilter.java

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    String header = request.getHeader("Authorization");

    if (header == null || !header.startsWith("Digest ")) {
        chain.doFilter(request, response);

        return;//from  ww w . j av a 2 s .  c o  m
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Digest Authorization header received from user agent: " + header);
    }

    DigestData digestAuth = new DigestData(header);

    try {
        digestAuth.validateAndDecode(this.authenticationEntryPoint.getKey(),
                this.authenticationEntryPoint.getRealmName());
    } catch (BadCredentialsException e) {
        fail(request, response, e);

        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 cacheWasUsed = true;
    UserDetails user = this.userCache.getUserFromCache(digestAuth.getUsername());
    String serverDigestMd5;

    try {
        if (user == null) {
            cacheWasUsed = false;
            user = this.userDetailsService.loadUserByUsername(digestAuth.getUsername());

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

            this.userCache.putUserInCache(user);
        }

        serverDigestMd5 = digestAuth.calculateServerDigest(user.getPassword(), request.getMethod());

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

            user = this.userDetailsService.loadUserByUsername(digestAuth.getUsername());
            this.userCache.putUserInCache(user);
            serverDigestMd5 = digestAuth.calculateServerDigest(user.getPassword(), request.getMethod());
        }

    } catch (UsernameNotFoundException notFound) {
        fail(request, response,
                new BadCredentialsException(
                        this.messages.getMessage("DigestAuthenticationFilter.usernameNotFound",
                                new Object[] { digestAuth.getUsername() }, "Username {0} not found")));

        return;
    }

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

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

    // To get this far, the digest must have been valid
    // Check the nonce has not expired
    // We do this last so we can direct the user agent its nonce is stale
    // but the request was otherwise appearing to be valid
    if (digestAuth.isNonceExpired()) {
        fail(request, response, new NonceExpiredException(this.messages
                .getMessage("DigestAuthenticationFilter.nonceExpired", "Nonce has expired/timed out")));

        return;
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Authentication success for user: '" + digestAuth.getUsername() + "' with response: '"
                + digestAuth.getResponse() + "'");
    }

    Authentication authentication = createSuccessfulAuthentication(request, user);
    SecurityContext context = SecurityContextHolder.createEmptyContext();
    context.setAuthentication(authentication);
    SecurityContextHolder.setContext(context);

    chain.doFilter(request, response);
}

From source file:org.springframework.ws.soap.security.x509.populator.DaoX509AuthoritiesPopulator.java

public UserDetails getUserDetails(X509Certificate clientCert) throws AuthenticationException {
    String subjectDN = clientCert.getSubjectDN().getName();

    Matcher matcher = subjectDNPattern.matcher(subjectDN);

    if (!matcher.find()) {
        throw new BadCredentialsException(messages.getMessage("DaoX509AuthoritiesPopulator.noMatching",
                new Object[] { subjectDN }, "No matching pattern was found in subjectDN: {0}"));
    }//w w w  . j av  a  2  s.c o m

    if (matcher.groupCount() != 1) {
        throw new IllegalArgumentException("Regular expression must contain a single group ");
    }

    String userName = matcher.group(1);

    UserDetails user = this.userDetailsService.loadUserByUsername(userName);

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

    return user;
}

From source file:org.springframework.ws.soap.security.x509.X509AuthenticationProvider.java

/**
 * If the supplied authentication token contains a certificate then this will be passed to the configured
 * {@link X509AuthoritiesPopulator} to obtain the user details and authorities for the user identified by the
 * certificate.<p>If no certificate is present (for example, if the filter is applied to an HttpRequest for
 * which client authentication hasn't been configured in the container) then a BadCredentialsException will be
 * raised.</p>/*w  w  w . j  a va2  s .c  o  m*/
 *
 * @param authentication the authentication request.
 *
 * @return an X509AuthenticationToken containing the authorities of the principal represented by the certificate.
 *
 * @throws AuthenticationException if the {@link X509AuthoritiesPopulator} rejects the certficate.
 * @throws BadCredentialsException if no certificate was presented in the authentication request.
 */
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (!supports(authentication.getClass())) {
        return null;
    }

    if (logger.isDebugEnabled()) {
        logger.debug("X509 authentication request: " + authentication);
    }

    X509Certificate clientCertificate = (X509Certificate) authentication.getCredentials();

    if (clientCertificate == null) {
        throw new BadCredentialsException(
                messages.getMessage("X509AuthenticationProvider.certificateNull", "Certificate is null"));
    }

    UserDetails user = userCache.getUserFromCache(clientCertificate);

    if (user == null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Authenticating with certificate " + clientCertificate);
        }
        user = x509AuthoritiesPopulator.getUserDetails(clientCertificate);
        userCache.putUserInCache(clientCertificate, user);
    }

    X509AuthenticationToken result = new X509AuthenticationToken(user, clientCertificate,
            user.getAuthorities());

    result.setDetails(authentication.getDetails());

    return result;
}

From source file:org.yes.cart.service.domain.aspect.impl.CustomerRegistrationAspect.java

/**
 * Perform notification about person registration.
 *
 * @param pjp join point//from w w  w  .j  av a2 s .c o m
 * @param generatePassword in case if new person was created.
 * @param resetPassword in case if this is password reset.
 * @param template template for email.
 * @return inherited return
 * @throws Throwable in case it was in underlying method
 */
protected Object notifyInternal(final ProceedingJoinPoint pjp, final boolean generatePassword,
        final boolean resetPassword, final String template) throws Throwable {
    final Object[] args = pjp.getArgs();

    final RegisteredPerson registeredPerson = (RegisteredPerson) args[0];
    final Shop shopArg = (Shop) args[1];
    final Shop shop = shopArg.getMaster() != null ? shopArg.getMaster() : shopArg;
    final String token = resetPassword ? (String) args[2] : null;

    if (isRegisteredPersonGuest(registeredPerson)) {
        // Do not send registration notification to guests
        return pjp.proceed();
    }

    final String generatedPassword;
    final String generatedPasswordHash;
    final String generatedToken;
    final Date generatedTokenExpiry;
    if (generatePassword) {

        if (StringUtils.isNotBlank(registeredPerson.getPassword())) {
            // We need to use password from RegisteredPerson because we auto-login using it during registration
            generatedPassword = registeredPerson.getPassword();
        } else {
            // fallback as we must have a password (worst case customer will need to reset the password)
            generatedPassword = phrazeGenerator.getNextPassPhrase();
        }
        // regenerate hash for new password
        generatedPasswordHash = passwordHashHelper.getHash(generatedPassword);
        generatedToken = null;
        generatedTokenExpiry = null;

    } else if (resetPassword) {
        if (StringUtils.isNotBlank(token)) {
            // Token is present so need to actually reset
            if (!isCallcenterToken(shop, token)) {
                if (!token.equals(registeredPerson.getAuthToken())
                        || registeredPerson.getAuthTokenExpiry() == null
                        || new Date().after(registeredPerson.getAuthTokenExpiry())) {
                    throw new BadCredentialsException(Constants.PASSWORD_RESET_AUTH_TOKEN_INVALID);
                }
            }

            // regenerate password
            generatedPassword = phrazeGenerator.getNextPassPhrase();
            generatedPasswordHash = passwordHashHelper.getHash(generatedPassword);
            generatedToken = null;
            generatedTokenExpiry = null;

        } else {
            // Token is null so this is a new password reset request
            generatedPassword = null;
            generatedPasswordHash = registeredPerson.getPassword(); // same as before
            generatedToken = phrazeGenerator.getNextPassPhrase();
            generatedTokenExpiry = determineExpiryTime(shop);
        }
    } else {
        generatedPassword = null;
        generatedPasswordHash = registeredPerson.getPassword(); // same as before
        generatedToken = null;
        generatedTokenExpiry = null;
    }

    final RegistrationMessage registrationMessage = createRegistrationMessage(generatePassword,
            registeredPerson, shop, generatedPassword, generatedPasswordHash, generatedToken,
            generatedTokenExpiry, template);

    sendNotification(registrationMessage);

    LOG.info("Person message was send to queue {}", registrationMessage);

    return pjp.proceed();
}

From source file:org.yes.cart.web.aspect.RegistrationAspect.java

/**
 * Perform notification about person registration.
 *
 * @param pjp join point/*w w  w .j a va 2 s .co m*/
 * @param newPerson in case if new person was created.
 * @return inherited return
 * @throws Throwable in case it was in underlying method
 */
protected Object notifyInternal(final ProceedingJoinPoint pjp, final boolean newPerson) throws Throwable {
    final Object[] args = pjp.getArgs();

    final RegisteredPerson registeredPerson = (RegisteredPerson) args[0];
    final Shop shop = (Shop) args[1];
    final String token = !newPerson ? (String) args[2] : null;

    final String generatedPassword;
    final String generatedPasswordHash;
    final String generatedToken;
    final Date generatedTokenExpiry;
    if (newPerson) {

        if (StringUtils.isNotBlank(registeredPerson.getPassword())) {
            // We need to use password from RegisteredPerson because we auto-login using it during registration
            generatedPassword = registeredPerson.getPassword();
        } else {
            // fallback as we must have a password (worst case customer will need to reset the password)
            generatedPassword = phrazeGenerator.getNextPassPhrase();
        }
        // regenerate hash for new password
        generatedPasswordHash = passwordHashHelper.getHash(generatedPassword);
        generatedToken = null;
        generatedTokenExpiry = null;

    } else {
        if (StringUtils.isNotBlank(token)) {
            // Token is present so need to actually reset
            if (!isCallcenterToken(shop, token)) {
                if (!token.equals(registeredPerson.getAuthToken())
                        || registeredPerson.getAuthTokenExpiry() == null
                        || new Date().after(registeredPerson.getAuthTokenExpiry())) {
                    throw new BadCredentialsException(Constants.PASSWORD_RESET_AUTH_TOKEN_INVALID);
                }
            }

            // regenerate password
            generatedPassword = phrazeGenerator.getNextPassPhrase();
            generatedPasswordHash = passwordHashHelper.getHash(generatedPassword);
            generatedToken = null;
            generatedTokenExpiry = null;

        } else {
            // Token is null so this is a new password reset request
            generatedPassword = null;
            generatedPasswordHash = registeredPerson.getPassword(); // same as before
            generatedToken = phrazeGenerator.getNextPassPhrase();
            generatedTokenExpiry = determineExpiryTime(shop);
        }
    }

    registeredPerson.setPassword(generatedPasswordHash);
    registeredPerson.setAuthToken(generatedToken);
    registeredPerson.setAuthTokenExpiry(generatedTokenExpiry);

    final RegistrationMessage registrationMessage = new RegistrationMessageImpl();
    registrationMessage.setEmail(registeredPerson.getEmail());
    registrationMessage.setFirstname(registeredPerson.getFirstname());
    registrationMessage.setLastname(registeredPerson.getLastname());
    registrationMessage.setPassword(generatedPassword);
    registrationMessage.setAuthToken(generatedToken);
    final ShoppingCart cart = ApplicationDirector.getShoppingCart();
    if (cart != null) {
        registrationMessage.setLocale(cart.getCurrentLocale());
    }

    registrationMessage.setMailTemplatePathChain(themeService.getMailTemplateChainByShopId(shop.getShopId()));

    registrationMessage.setTemplateName(newPerson ? "customer-registered" : "customer-change-password");

    registrationMessage.setShopMailFrom(determineFromEmail(shop));

    registrationMessage.setShopId(shop.getShopId());
    registrationMessage.setShopCode(shop.getCode());
    registrationMessage.setShopName(shop.getName());
    registrationMessage.setShopUrl(transformShopUrls(shop));

    sendNotification(registrationMessage);

    ShopCodeContext.getLog(this).info("Person message was send to queue {}", registrationMessage);

    return pjp.proceed();
}

From source file:pl.bcichecki.rms.customizations.org.springframework.security.web.authentication.www.EventPublisherAwareDigestAuthenticationFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    String header = request.getHeader("Authorization");

    if (header == null || !header.startsWith("Digest ")) {
        chain.doFilter(request, response);

        return;/*from w w w  . j  ava2 s.co  m*/
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Digest Authorization header received from user agent: " + header);
    }

    DigestData digestAuth = new DigestData(header);

    try {
        digestAuth.validateAndDecode(authenticationEntryPoint.getKey(),
                authenticationEntryPoint.getRealmName());
    } catch (BadCredentialsException e) {
        fail(request, response, e);

        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 cacheWasUsed = true;
    UserDetails user = userCache.getUserFromCache(digestAuth.getUsername());
    String serverDigestMd5;

    try {
        if (user == null) {
            cacheWasUsed = false;
            user = userDetailsService.loadUserByUsername(digestAuth.getUsername());

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

            userCache.putUserInCache(user);
        }

        serverDigestMd5 = digestAuth.calculateServerDigest(user.getPassword(), request.getMethod());

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

            user = userDetailsService.loadUserByUsername(digestAuth.getUsername());
            userCache.putUserInCache(user);
            serverDigestMd5 = digestAuth.calculateServerDigest(user.getPassword(), request.getMethod());
        }

    } catch (UsernameNotFoundException notFound) {
        // MODIFICATION

        boolean userWasNull = false;
        if (user == null) {
            userWasNull = true;
            user = new User(digestAuth.getUsername(), "fakePassSoSpringShutUp", false, false, false, false,
                    new ArrayList<GrantedAuthority>());
        }

        authenticationEventPublisher.publishAuthenticationFailure(notFound,
                createUnsuccessfulAuthentication(request, user));

        if (userWasNull) {
            user = null;
        }

        // END OF MODIFICATION

        fail(request, response,
                new BadCredentialsException(messages.getMessage("DigestAuthenticationFilter.usernameNotFound",
                        new Object[] { digestAuth.getUsername() }, "Username {0} not found")));

        return;
    }

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

        // MODIFICATION

        authenticationEventPublisher.publishAuthenticationFailure(
                new BadCredentialsException("Bad credentials"),
                createUnsuccessfulAuthentication(request, user));

        // END OF MODIFICATION

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

    // To get this far, the digest must have been valid
    // Check the nonce has not expired
    // We do this last so we can direct the user agent its nonce is stale
    // but the request was otherwise appearing to be valid
    if (digestAuth.isNonceExpired()) {
        fail(request, response, new NonceExpiredException(
                messages.getMessage("DigestAuthenticationFilter.nonceExpired", "Nonce has expired/timed out")));

        return;
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Authentication success for user: '" + digestAuth.getUsername() + "' with response: '"
                + digestAuth.getResponse() + "'");
    }

    SecurityContextHolder.getContext().setAuthentication(createSuccessfulAuthentication(request, user));

    chain.doFilter(request, response);
}