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:com.springsource.hq.plugin.tcserver.serverconfig.web.support.HqAuthenticationFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    /**//from  www  . ja v  a 2s .  com
     * If authentication isn't empty, look for the chance that the user was authenticated by
     * AnonymousAuthenticationProvider. If this is the case, there will be security credentials, but no session role
     * granted yet. The filter pulls sessionId from the session, and checks against HQ. If successful, it replaces
     * the existing token with an HQ-specific one.
     * 
     * If there is already an HqAuthenticationToken then grab the token's sessionId, and re-verify that the session
     * is active. If the sessionId is null (which only happens when manually entering URLs), send user down the
     * filter stack.
     * 
     * If there is no HqAuthenticationToken at all (which should only happen if there is a faulty change in
     * configuration), then go down the filter stack, allowing Spring Security to fail on lack of security
     * credentials. Spring Security tends to throw some sort of meaningful error indicating what is missing.
     */
    if (auth != null) {
        logger.debug("Authentication exists => " + auth);
        String sessionId = request.getParameter("sessionId");
        if (sessionId != null) {
            logger.debug("SessionId found => " + sessionId);

            if (!sessionIdExpired(request, sessionId)) {

                UsernamePasswordAuthenticationToken newToken = createHqAuthenticationToken(auth, sessionId);
                logger.debug("Replacing existing authentication with new one => " + newToken);
                SecurityContextHolder.getContext().setAuthentication(newToken);

            }
        } else {
            if (auth instanceof HqAuthenticationToken) {
                HqAuthenticationToken token = (HqAuthenticationToken) auth;
                if (sessionIdExpired(request, token.getSessionId())) {
                    throw new BadCredentialsException("Session has expired. Re-login.");
                }
            } else {
                logger.debug("sessionId not found at all. Unable to check against Hyperic.");
            }
        }
    } else {
        logger.debug("Authentication is currently empty. Unable to check against Hyperic.");
    }

    chain.doFilter(request, response);
}

From source file:eu.supersede.fe.security.SecurityConfiguration.java

@Bean
AuthenticationProvider customAuthenticationProvider() {
    return new AuthenticationProvider() {
        private final Logger log = LoggerFactory.getLogger(this.getClass());

        @Override/*from ww  w. j a va 2  s  . c  om*/
        @Transactional
        public Authentication authenticate(Authentication auth) throws AuthenticationException {
            String username = (String) auth.getPrincipal();
            String password = (String) auth.getCredentials();

            ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder
                    .currentRequestAttributes();
            HttpServletRequest req = attr.getRequest();
            String tenantId = req.getHeader("TenantId");

            if (tenantId == null) {
                log.error("Tenant provided");
                throw new BadCredentialsException("Invalid login request: missing tenant");
            }

            AuthorizationToken token = getAuthToken(username, password, tenantId);
            User user = users.findByUsername(username);

            if (user == null) {
                log.error("Username not found in Database");
                throw new BadCredentialsException("Invalid login request: user " + username + " not found");
            }

            // get authorities from profiles
            List<Profile> profiles = user.getProfiles();
            String[] authorities = new String[profiles.size()];

            for (int i = 0; i < profiles.size(); i++) {
                authorities[i] = "ROLE_" + profiles.get(i).getName();
            }

            log.debug("User has " + authorities.length + " authorities");

            List<GrantedAuthority> permissions = AuthorityUtils.createAuthorityList(authorities);
            DatabaseUser dbUser = new DatabaseUser(user.getUserId(),
                    user.getFirstName() + " " + user.getLastName(), user.getEmail(), password, token, true,
                    true, true, true, permissions, user.getLocale());

            return new UsernamePasswordAuthenticationToken(dbUser, password, permissions);// AUTHORITIES
        }

        private AuthorizationToken getAuthToken(String username, String password, String tenantId) {
            AuthorizationToken token = null;

            if (AUTH_MANAGER_ENABLED) {
                try {
                    token = proxy.getIFAuthenticationManager(tenantId).getAuthorizationToken(username, password,
                            tenantId);
                } catch (HttpClientErrorException e) {
                    log.error("Invalid username and password.");
                } catch (NullPointerException e1) {
                    log.error("Authorization token is null, check your if.properties file in the conf/ folder");
                } catch (Exception e2) {
                    e2.printStackTrace();
                }

                if (token == null || token.getAccessToken() == null) {
                    log.error("Supersede integration token is null");
                    throw new BadCredentialsException(
                            "Invalid login request: authentication manager token is null");
                }
            } else {
                log.warn("IF Authentication Manager disable, user token is NULL");
            }

            return token;
        }

        @Override
        @SuppressWarnings("rawtypes")
        public boolean supports(Class authentication) {
            return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
        }
    };
}

From source file:com.erudika.para.security.GoogleAuthFilter.java

/**
 * Handles an authentication request.//  ww  w . java2 s.c  om
 * @param request HTTP request
 * @param response HTTP response
 * @return an authentication object that contains the principal object if successful.
 * @throws IOException ex
 */
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    final String requestURI = request.getRequestURI();
    UserAuthentication userAuth = null;

    if (requestURI.endsWith(GOOGLE_ACTION)) {
        String authCode = request.getParameter("code");
        if (!StringUtils.isBlank(authCode)) {
            String entity = Utils.formatMessage(PAYLOAD, URLEncoder.encode(authCode, "UTF-8"),
                    URLEncoder.encode(request.getRequestURL().toString(), "UTF-8"), Config.GPLUS_APP_ID,
                    Config.GPLUS_SECRET);

            HttpPost tokenPost = new HttpPost(TOKEN_URL);
            tokenPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
            tokenPost.setEntity(new StringEntity(entity, "UTF-8"));
            CloseableHttpResponse resp1 = httpclient.execute(tokenPost);

            if (resp1 != null && resp1.getEntity() != null) {
                Map<String, Object> token = jreader.readValue(resp1.getEntity().getContent());
                if (token != null && token.containsKey("access_token")) {
                    userAuth = getOrCreateUser(null, (String) token.get("access_token"));
                }
                EntityUtils.consumeQuietly(resp1.getEntity());
            }
        }
    }

    User user = SecurityUtils.getAuthenticatedUser(userAuth);

    if (userAuth == null || user == null || user.getIdentifier() == null) {
        throw new BadCredentialsException("Bad credentials.");
    } else if (!user.getActive()) {
        throw new LockedException("Account is locked.");
    }
    return userAuth;
}

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

/**
 * Check password is valid?/*from ww  w .  ja v  a 2s  .  co m*/
 *
 * @param encPass     - a pre-encoded password
 * @param credentials Credentials(always was password)
 * @param salt        - a salt value.
 * @throws org.springframework.security.authentication.BadCredentialsException if credentials invalid
 */
protected void checkCredentials(String encPass, String credentials, String salt) {
    if (!Crypto.passwdValid(encPass, credentials, salt)) {
        throw new BadCredentialsException(messages
                .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
    }
}

From source file:com.formkiq.core.service.SpringSecurityService.java

/**
 * Returns user by email only if admin, otherwise
 * current user.//from   w w  w .  j  a va  2 s .co m
 * @param email {@link String}
 * @return {@link UserDetails}
 */
public UserDetails getUserDetailsByEmail(final String email) {

    UserDetails user = getUserDetails();

    if (isAdmin() && !StringUtils.isEmpty(email)) {
        // TODO test invalid email
        UserDetails euser = this.userservice.findUserByEmail(email);
        if (euser != null) {
            user = euser;
        }
    }

    if (user == null) {
        throw new BadCredentialsException("User is not authenticated");
    }

    return user;
}

From source file:com.erudika.para.security.GitHubAuthFilter.java

/**
 * Handles an authentication request.//from w  w w .j ava 2  s .  c  o  m
 * @param request HTTP request
 * @param response HTTP response
 * @return an authentication object that contains the principal object if successful.
 * @throws IOException ex
 */
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    final String requestURI = request.getRequestURI();
    UserAuthentication userAuth = null;

    if (requestURI.endsWith(GITHUB_ACTION)) {
        String authCode = request.getParameter("code");
        if (!StringUtils.isBlank(authCode)) {
            String entity = Utils.formatMessage(PAYLOAD, URLEncoder.encode(authCode, "UTF-8"),
                    URLEncoder.encode(request.getRequestURL().toString(), "UTF-8"), Config.GITHUB_APP_ID,
                    Config.GITHUB_SECRET);

            HttpPost tokenPost = new HttpPost(TOKEN_URL);
            tokenPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
            tokenPost.setHeader(HttpHeaders.ACCEPT, "application/json");
            tokenPost.setEntity(new StringEntity(entity, "UTF-8"));
            CloseableHttpResponse resp1 = httpclient.execute(tokenPost);

            if (resp1 != null && resp1.getEntity() != null) {
                Map<String, Object> token = jreader.readValue(resp1.getEntity().getContent());
                if (token != null && token.containsKey("access_token")) {
                    userAuth = getOrCreateUser(null, (String) token.get("access_token"));
                }
                EntityUtils.consumeQuietly(resp1.getEntity());
            }
        }
    }

    User user = SecurityUtils.getAuthenticatedUser(userAuth);

    if (userAuth == null || user == null || user.getIdentifier() == null) {
        throw new BadCredentialsException("Bad credentials.");
    } else if (!user.getActive()) {
        throw new LockedException("Account is locked.");
    }
    return userAuth;
}

From source file:net.ljcomputing.ecsr.security.service.impl.JwtTokenServiceImpl.java

/**
 * @see net.ljcomputing.ecsr.security.service.impl.JwtTokenService
 *    #create(org.springframework.security.core.Authentication)
 *//*from  ww  w  . j a v  a  2s  .  c o m*/
@Override
public String create(final Authentication authentication) {
    if (authentication == null) {
        LOGGER.error("NO TOKEN");
        throw new BadCredentialsException("No authentication provided.");
    }

    final String authorities = authentication.getAuthorities().stream() // NOPMD
            .map(authority -> authority.getAuthority()).collect(Collectors.joining(","));

    final String result = Jwts.builder() // NOPMD
            .setSubject(authentication.getName()).setIssuer(tokenIssuer).setIssuedAt(now())
            .setExpiration(expirationDate()).claim(WebSecurityConfiguration.AUTHORITIES_KEY, authorities)
            .signWith(SignatureAlgorithm.HS512, tokenSigningKey).compact();

    if (!isValid(result)) {
        throw new BadCredentialsException("Token is invalid");
    }

    return result;
}

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

/**
 * @see de.hybris.platform.spring.security.CoreAuthenticationProvider#additionalAuthenticationChecks(org.springframework.security.core.userdetails.UserDetails,
 *      org.springframework.security.authentication.AbstractAuthenticationToken)
 *//*from   www  .  j a v a 2s .  co m*/
@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");
    }

    // Check if the user is in role admingroup
    if (getAdminAuthority() != null && details.getAuthorities().contains(getAdminAuthority())) {
        throw new LockedException("Login attempt as " + Constants.USER.ADMIN_USERGROUP + " is rejected");
    }

    // Check if the customer is B2B type
    if (!getB2bUserGroupProvider().isUserAuthorized(details.getUsername())) {
        throw new InsufficientAuthenticationException(
                messages.getMessage("checkout.error.invalid.accountType", "You are not allowed to login"));
    }

    if (!getB2bUserGroupProvider().isUserEnabled(details.getUsername())) {
        throw new DisabledException("User " + details.getUsername() + " is disabled... "
                + messages.getMessage("text.company.manage.units.disabled"));
    }
}

From source file:com.acc.storefront.security.AcceleratorAuthenticationProvider.java

/**
 * @see de.hybris.platform.spring.security.CoreAuthenticationProvider#additionalAuthenticationChecks(org.springframework.security.core.userdetails.UserDetails,
 *      org.springframework.security.authentication.AbstractAuthenticationToken)
 *//*w w  w .j ava 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");
    }

    // Check if the user is in role admingroup
    if (getAdminAuthority() != null && details.getAuthorities().contains(getAdminAuthority())) {
        throw new LockedException("Login attempt as " + Constants.USER.ADMIN_USERGROUP + " is rejected");
    }
}

From source file:fr.univrouen.poste.provider.DatabaseAuthenticationProvider.java

@Override
@Transactional(noRollbackFor = BadCredentialsException.class)
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication)
        throws AuthenticationException {

    UserDetails userDetails = null;/* w ww  . ja va 2  s . com*/

    logger.debug("Inside retrieveUser");

    WebAuthenticationDetails wad = (WebAuthenticationDetails) authentication.getDetails();
    String userIPAddress = wad.getRemoteAddress();

    Boolean ipCanBeUsed4AuthAdminManager = this.isIpCanBeUsed4AuthAdminManager(userIPAddress);

    username = username.toLowerCase();

    String password = (String) authentication.getCredentials();
    if (!StringUtils.hasText(password) || !StringUtils.hasText(username)) {
        logService.logActionAuth(LogService.AUTH_FAILED, username, userIPAddress);
        throw new BadCredentialsException("Merci de saisir votre email et mot de passe");
    }
    String encryptedPassword = messageDigestPasswordEncoder.encodePassword(password, null);
    List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    Boolean enabled;

    try {
        TypedQuery<User> query = User.findUsersByEmailAddress(username, null, null);

        User targetUser = (User) query.getSingleResult();

        if (targetUser.isLocked()) {
            throw new BadCredentialsException("Compte vrouill, merci de retenter d'ici quelques secondes.");
        }

        // authenticate the person
        String expectedPassword = targetUser.getPassword();
        if (!StringUtils.hasText(expectedPassword)) {
            logService.logActionAuth(LogService.AUTH_FAILED, username, userIPAddress);
            throw new BadCredentialsException("Aucun mot de passe pour " + username
                    + " n'est enregistr dans la base, merci d'activer votre compte via le lien d'activation envoy par email. Contactez un administrateur si problme.");
        }
        if (!encryptedPassword.equals(expectedPassword)) {
            logService.logActionAuth(LogService.AUTH_FAILED, username, userIPAddress);
            throw new BadCredentialsException("Email utilisateur ou mot de passe invalide.");
        }

        // restriction accs rseau
        if (!ipCanBeUsed4AuthAdminManager
                && (targetUser.getIsAdmin() || targetUser.getIsSuperManager() || targetUser.getIsManager())) {
            logService.logActionAuth(LogService.AUTH_FAILED, username, userIPAddress);
            logger.warn("User " + username
                    + " tried to access to his admin/manager/supermanager account from this IP "
                    + userIPAddress);
            throw new BadCredentialsException(
                    "Vous ne pouvez pas vous authentifier sur ce compte depuis cet accs rseau. Contactez un administrateur si problme.");
        }

        // restriction dates accs pour candidats et membres 
        boolean isCurrentTimeOk4ThisCandidat = dateClotureChecker.isCurrentTimeOk4ThisCandidat(targetUser);
        boolean isCurrentTimeOk4ThisMembre = dateClotureChecker.isCurrentTimeOk4ThisMembre(targetUser);
        if ((targetUser.getIsCandidat() || targetUser.getIsMembre()) && !isCurrentTimeOk4ThisCandidat
                && !isCurrentTimeOk4ThisMembre) {
            if (targetUser.getIsCandidat() && !isCurrentTimeOk4ThisCandidat) {
                logger.warn("User " + username
                        + " tried to access to his candidat account but the dateEndCandidat is < current time");
            }
            if (targetUser.getIsMembre() && !isCurrentTimeOk4ThisMembre) {
                logger.warn("User " + username
                        + " tried to access to his membre account but the dateEndMembre is < current time");
            }
            logService.logActionAuth(LogService.AUTH_FAILED, username, userIPAddress);
            throw new BadCredentialsException(
                    "La date de clture des dpts est dpasse, vous ne pouvez maintenant plus accder  l'application.");
        }

        userDetails = databaseUserDetailsService.loadUserByUser(targetUser);

    } catch (EmptyResultDataAccessException e) {
        logService.logActionAuth(LogService.AUTH_FAILED, username, userIPAddress);
        throw new BadCredentialsException("Compte utilisateur et/ou mot de passe invalide");
    } catch (EntityNotFoundException e) {
        logService.logActionAuth(LogService.AUTH_FAILED, username, userIPAddress);
        throw new BadCredentialsException("Compte utilisateur et/ou mot de passe invalide");
    } catch (NonUniqueResultException e) {
        logService.logActionAuth(LogService.AUTH_FAILED, username, userIPAddress);
        throw new BadCredentialsException("Utilisateur non unique, contactez l'administrateur.");
    }

    logService.logActionAuth(LogService.AUTH_SUCCESS, username, userIPAddress);

    return userDetails;
}