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.taverna.server.master.identity.StrippedDownAuthProvider.java

@PerfLogged
@Override/*w  w  w .  j a va2  s  .com*/
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    if (!(authentication instanceof UsernamePasswordAuthenticationToken))
        throw new IllegalArgumentException("can only authenticate against username+password");
    UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication;

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

    UserDetails user;

    try {
        user = retrieveUser(username, auth);
        if (user == null)
            throw new IllegalStateException(
                    "retrieveUser returned null - a violation of the interface contract");
    } catch (UsernameNotFoundException notFound) {
        if (logger.isDebugEnabled())
            logger.debug("User '" + username + "' not found", notFound);
        throw new BadCredentialsException("Bad credentials");
    }

    // Pre-auth
    if (!user.isAccountNonLocked())
        throw new LockedException("User account is locked");
    if (!user.isEnabled())
        throw new DisabledException("User account is disabled");
    if (!user.isAccountNonExpired())
        throw new AccountExpiredException("User account has expired");
    Object credentials = auth.getCredentials();
    if (credentials == null) {
        logger.debug("Authentication failed: no credentials provided");

        throw new BadCredentialsException("Bad credentials");
    }

    String providedPassword = credentials.toString();
    boolean matched = false;
    synchronized (authCache) {
        AuthCacheEntry pw = authCache.get(username);
        if (pw != null && providedPassword != null) {
            if (pw.valid(providedPassword))
                matched = true;
            else
                authCache.remove(username);
        }
    }
    // Auth
    if (!matched) {
        if (!passwordEncoder.matches(providedPassword, user.getPassword())) {
            logger.debug("Authentication failed: password does not match stored value");

            throw new BadCredentialsException("Bad credentials");
        }
        if (providedPassword != null)
            synchronized (authCache) {
                authCache.put(username, new AuthCacheEntry(providedPassword));
            }
    }

    // Post-auth
    if (!user.isCredentialsNonExpired())
        throw new CredentialsExpiredException("User credentials have expired");

    return createSuccessAuthentication(user, auth, user);
}

From source file:org.syncope.core.security.SyncopeAuthenticationProvider.java

@Override
@Transactional(noRollbackFor = { BadCredentialsException.class })
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {

    boolean authenticated;
    SyncopeUser passwordUser = new SyncopeUser();
    SyncopeUser user = null;//from ww w .j a  va 2  s .  c om

    if (adminUser.equals(authentication.getPrincipal())) {
        passwordUser.setPassword(authentication.getCredentials().toString(), CipherAlgorithm.MD5, 0);

        authenticated = adminMD5Password.equalsIgnoreCase(passwordUser.getPassword());
    } else {
        String username;
        try {
            username = authentication.getPrincipal().toString();
        } catch (NumberFormatException e) {
            throw new UsernameNotFoundException("Invalid username: " + authentication.getName(), e);
        }

        user = userDAO.find(username);
        if (user == null) {
            throw new UsernameNotFoundException("Could not find user " + username);
        }

        passwordUser.setPassword(authentication.getCredentials().toString(), user.getCipherAlgoritm(), 0);

        authenticated = user.getPassword().equalsIgnoreCase(passwordUser.getPassword());
    }

    Authentication result;

    if ((user == null || !user.getSuspended()) && authenticated) {
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
                authentication.getPrincipal(), null, userDetailsService
                        .loadUserByUsername(authentication.getPrincipal().toString()).getAuthorities());
        token.setDetails(authentication.getDetails());

        result = token;

        LOG.debug("User {} authenticated with roles {}", authentication.getPrincipal(), token.getAuthorities());

        if (user != null) {
            user.setLastLoginDate(new Date());
            user.setFailedLogins(0);
            userDAO.save(user);
        }

    } else {
        result = authentication;

        if (user != null && !user.getSuspended()) {
            user.setFailedLogins(user.getFailedLogins() + 1);
            userDAO.save(user);
        }

        LOG.debug("User {} not authenticated", authentication.getPrincipal());

        throw new BadCredentialsException("User " + authentication.getPrincipal() + " not authenticated");
    }

    return result;
}

From source file:net.firejack.platform.web.security.spring.AuthenticationManager.java

protected Authentication doAuthentication(Authentication authentication) throws AuthenticationException {
    if (authentication.getPrincipal() == null || authentication.getCredentials() == null
            || authentication.getDetails() == null) {
        String errorMessage = MessageResolver.messageFormatting("login.wrong.credentials", null);
        throw new BadCredentialsException(errorMessage);
    }//  w  w  w.j  a v a 2 s  .  c om

    String userName = authentication.getPrincipal().toString();
    String password = authentication.getCredentials().toString();
    HttpSession session = ((AuthenticationToken) authentication).getSession();

    if (StringUtils.isNotBlank(userName) && StringUtils.isNotBlank(password)) {
        if (!getAuthenticators().isEmpty()) {
            AuthenticatorFactory authenticatorFactory = AuthenticatorFactory.getInstance();
            IAuthenticationSource authenticationSource = authenticatorFactory
                    .provideDefaultAuthenticationSource(userName, password);
            for (IAuthenticator authenticator : getAuthenticators()) {
                IAuthenticationDetails authenticationDetails = authenticator.authenticate(authenticationSource);
                if (authenticationDetails != null) {
                    return generateDefaultToken(authenticationDetails, session);
                }
            }
        }
    }

    String errorMessage = MessageResolver.messageFormatting("login.authentication.failure", null);
    throw new BadCredentialsException(errorMessage);
}

From source file:com.hp.autonomy.frontend.configuration.authentication.CommunityAuthenticationProvider.java

@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
    final com.hp.autonomy.frontend.configuration.authentication.Authentication<?> authenticationConfig = configService
            .getConfig().getAuthentication();
    final String authenticationMethod = authenticationConfig.getMethod();

    if (!(authenticationConfig instanceof CommunityAuthentication)
            || LoginTypes.DEFAULT.equals(authenticationMethod)) {
        return null;
    }//from  ww  w.j  a  v a  2  s . c  o m

    final String username = authentication.getName();
    final String password = authentication.getCredentials().toString();

    try {
        final boolean isAuthenticated = userService.authenticateUser(username, password, authenticationMethod);

        if (!isAuthenticated) {
            throw new BadCredentialsException("Bad credentials");
        }

        final UserRoles userRoles = userService.getUser(username, true);
        Set<String> roleNames = new HashSet<>(userRoles.getRoles());

        if (!roles.areRolesAuthorized(roleNames, loginPrivileges)) {
            // if we have default roles, grant the user the default roles
            if (!defaultRoles.isEmpty()) {
                roleNames = defaultRoles;

                // check that the default role names make sense
                if (!roles.areRolesAuthorized(roleNames, loginPrivileges)) {
                    throw new BadCredentialsException("Bad credentials");
                }
            } else {
                throw new BadCredentialsException("Bad credentials");
            }
        }

        final Collection<GrantedAuthority> grantedAuthorities = roleNames.stream()
                .map(SimpleGrantedAuthority::new).collect(Collectors.toList());

        final Collection<? extends GrantedAuthority> mappedAuthorities = authoritiesMapper
                .mapAuthorities(grantedAuthorities);

        return new UsernamePasswordAuthenticationToken(
                new CommunityPrincipal(userRoles.getUid(), username, userRoles.getSecurityInfo(), roleNames),
                password, mappedAuthorities);
    } catch (final AciErrorException aciError) {
        // This should not happen
        throw new InternalAuthenticationServiceException(
                "An ACI error occurred while attempting to authenticate", aciError);
    } catch (final AciServiceException serviceError) {
        // This will happen if community is down
        throw new InternalAuthenticationServiceException("An error occurred while contacting community",
                serviceError);
    }
}

From source file:com.haulmont.restapi.ldap.LdapAuthController.java

@RequestMapping(value = "/v2/ldap/token", method = RequestMethod.POST)
public ResponseEntity<OAuth2AccessToken> postAccessToken(Principal principal,
        @RequestParam Map<String, String> parameters, HttpServletRequest request)
        throws HttpRequestMethodNotSupportedException {

    if (!ldapConfig.getLdapEnabled()) {
        log.debug("LDAP authentication is disabled. Property cuba.rest.ldap.enabled is false");

        throw new InvalidGrantException("LDAP is not supported");
    }//from www .j av a 2s.c  o  m

    if (!(principal instanceof Authentication)) {
        throw new InsufficientAuthenticationException(
                "There is no client authentication. Try adding an appropriate authentication filter.");
    }

    String grantType = parameters.get(OAuth2Utils.GRANT_TYPE);
    if (!"password".equals(grantType)) {
        throw new InvalidGrantException("grant type not supported for ldap/token endpoint");
    }

    String username = parameters.get("username");

    if (restApiConfig.getStandardAuthenticationUsers().contains(username)) {
        log.info("User {} is not allowed to use external login in REST API", username);
        throw new BadCredentialsException("Bad credentials");
    }

    String ipAddress = request.getRemoteAddr();

    String password = parameters.get("password");

    OAuth2AccessTokenResult tokenResult = authenticate(username, password, request.getLocale(), ipAddress,
            parameters);

    return ResponseEntity.ok(tokenResult.getAccessToken());
}

From source file:com.haulmont.restapi.auth.CubaUserAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
            .currentRequestAttributes();
    HttpServletRequest request = attributes.getRequest();

    String ipAddress = request.getRemoteAddr();

    if (authentication instanceof UsernamePasswordAuthenticationToken) {
        RestApiConfig config = configuration.getConfig(RestApiConfig.class);
        if (!config.getStandardAuthenticationEnabled()) {
            log.debug(/*from  w ww . j  a  v a 2 s  .  c  om*/
                    "Standard authentication is disabled. Property cuba.rest.standardAuthenticationEnabled is false");

            throw new InvalidGrantException("Authentication disabled");
        }

        UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;

        String login = (String) token.getPrincipal();

        UserSession session;
        try {
            String passwordHash = passwordEncryption.getPlainHash((String) token.getCredentials());

            LoginPasswordCredentials credentials = new LoginPasswordCredentials(login, passwordHash);
            credentials.setIpAddress(ipAddress);
            credentials.setClientType(ClientType.REST_API);
            credentials.setClientInfo(makeClientInfo(request.getHeader(HttpHeaders.USER_AGENT)));

            //if the locale value is explicitly passed in the Accept-Language header then set its value to the
            //credentials. Otherwise, the locale of the user should be used
            Locale locale = restAuthUtils.extractLocaleFromRequestHeader(request);
            if (locale != null) {
                credentials.setLocale(locale);
                credentials.setOverrideLocale(true);
            } else {
                credentials.setOverrideLocale(false);
            }

            session = authenticationService.login(credentials).getSession();
        } catch (AccountLockedException le) {
            log.info("Blocked user login attempt: login={}, ip={}", login, ipAddress);
            throw new LockedException("User temporarily blocked");
        } catch (RestApiAccessDeniedException ex) {
            log.info("User is not allowed to use the REST API {}", login);
            throw new BadCredentialsException("User is not allowed to use the REST API");
        } catch (LoginException e) {
            log.info("REST API authentication failed: {} {}", login, ipAddress);
            throw new BadCredentialsException("Bad credentials");
        }

        AppContext.setSecurityContext(new SecurityContext(session));

        UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(
                authentication.getPrincipal(), authentication.getCredentials(),
                getRoleUserAuthorities(authentication));
        @SuppressWarnings("unchecked")
        Map<String, String> details = (Map<String, String>) authentication.getDetails();
        details.put(SESSION_ID_DETAILS_ATTRIBUTE, session.getId().toString());
        result.setDetails(details);
        return result;
    }

    return null;
}

From source file:com.alliander.osgp.shared.security.CustomAuthenticationManager.java

private void checkAuthenticationInstance(final Authentication authentication) {

    // Check if user has authentication instance.
    if (authentication == null) {
        LOGGER.debug(NULL_AUTHENTICATION);
        throw new BadCredentialsException(NULL_AUTHENTICATION);
    }/*ww w .  ja  va  2  s.c  om*/
}

From source file:com.ebay.pulsar.analytics.resources.PermissionControlResource.java

public String getUserName() {
    try {//from  w  w w  . j  av a2s .  c  o m
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth instanceof UsernamePasswordAuthenticationToken) {
            return ((UserDetails) auth.getPrincipal()).getUsername();
        } else if (auth instanceof AnonymousAuthenticationToken) {
            throw new BadCredentialsException("Bad credentials");
        } else {
            throw new BadCredentialsException("Bad credentials");
        }
    } catch (Exception e) {
        throw new BadCredentialsException("Bad credentials");
    }
}

From source file:org.cloudfoundry.identity.uaa.login.ClientInfoAuthenticationFilter.java

protected void validateClient(ClientDetails client) {
    String clientId = client.getClientId();
    for (String pattern : allowedClients) {
        if (!clientId.matches(pattern)) {
            throw new BadCredentialsException("Client not permitted: " + clientId);
        }/*from   w ww.  j  a  va  2 s  .  co  m*/
    }
    Set<String> grantTypes = client.getAuthorizedGrantTypes();
    boolean matched = false;
    for (String pattern : allowedGrantTypes) {
        for (String grantType : grantTypes) {
            if (grantType.matches(pattern)) {
                matched = true;
            }
        }
    }
    if (!matched) {
        throw new BadCredentialsException("Client not permitted (wrong grant type): " + clientId);
    }
}