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, Throwable t) 

Source Link

Document

Constructs a BadCredentialsException with the specified message and root cause.

Usage

From source file:de.theit.jenkins.crowd.CrowdAuthenticationManager.java

/**
 * {@inheritDoc}//from  w w  w.  j  a v a 2 s .co  m
 * 
 * @see org.springframework.security.AuthenticationManager#authenticate(org.springframework.security.Authentication)
 */
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String username = authentication.getPrincipal().toString();

    // checking whether there's already a SSO token
    if (null == authentication.getCredentials() && authentication instanceof CrowdAuthenticationToken
            && null != ((CrowdAuthenticationToken) authentication).getSSOToken()) {
        // SSO token available => user already authenticated
        if (LOG.isLoggable(Level.FINER)) {
            LOG.finer("User '" + username + "' already authenticated");
        }
        return authentication;
    }

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

    // ensure that the group is available, active and that the user
    // is a member of it
    if (!this.configuration.isGroupMember(username)) {
        throw new InsufficientAuthenticationException(
                userNotValid(username, this.configuration.allowedGroupNames));
    }

    String displayName = null;
    try {
        // authenticate user
        if (LOG.isLoggable(Level.FINE)) {
            LOG.fine("Authenticating user: " + username);
        }
        User user = this.configuration.crowdClient.authenticateUser(username, password);
        displayName = user.getDisplayName();
    } catch (UserNotFoundException ex) {
        if (LOG.isLoggable(Level.INFO)) {
            LOG.info(userNotFound(username));
        }
        throw new BadCredentialsException(userNotFound(username), ex);
    } catch (ExpiredCredentialException ex) {
        LOG.warning(expiredCredentials(username));
        throw new CredentialsExpiredException(expiredCredentials(username), ex);
    } catch (InactiveAccountException ex) {
        LOG.warning(accountExpired(username));
        throw new AccountExpiredException(accountExpired(username), ex);
    } catch (ApplicationPermissionException ex) {
        LOG.warning(applicationPermission());
        throw new AuthenticationServiceException(applicationPermission(), ex);
    } catch (InvalidAuthenticationException ex) {
        LOG.warning(invalidAuthentication());
        throw new AuthenticationServiceException(invalidAuthentication(), ex);
    } catch (OperationFailedException ex) {
        LOG.log(Level.SEVERE, operationFailed(), ex);
        throw new AuthenticationServiceException(operationFailed(), ex);
    }

    // user successfully authenticated
    // => retrieve the list of groups the user is a member of
    List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

    // add the "authenticated" authority to the list of granted
    // authorities...
    authorities.add(SecurityRealm.AUTHENTICATED_AUTHORITY);
    // ..and finally all authorities retrieved from the Crowd server
    authorities.addAll(this.configuration.getAuthoritiesForUser(username));

    // user successfully authenticated => create authentication token
    if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("User successfully authenticated; creating authentication token");
    }

    return new CrowdAuthenticationToken(username, password, authorities, null, displayName);
}

From source file:es.osoco.grails.plugins.otp.authentication.OneTimePasswordAuthenticationProvider.java

@SuppressWarnings("deprecation")
protected void additionalAuthenticationChecks(UserDetails userDetails,
        OneTimePasswordAuthenticationToken authentication) throws AuthenticationException {

    if (logger.isDebugEnabled()) {
        logger.debug("OneTimePasswordAuthenticationProvider for authentication "
                + authentication.getClass().getName());
    }// w  w  w.  j av a2s . c  o m

    if (authentication.getCredentials() == null) {
        logger.debug("Authentication failed: no credentials provided");

        throw new BadCredentialsException(messages
                .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"),
                isIncludeDetailsObject() ? userDetails : null);
    }

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

    if (!oneTimePasswordService.isPasswordValid(presentedPassword,
            ((GrailsOtpUser) userDetails).getSecretKey())) {
        logger.debug("Authentication failed: one time password is not valid");

        throw new BadCredentialsException(messages
                .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"),
                isIncludeDetailsObject() ? userDetails : null);
    }
}

From source file:com.skywell.social.custom.OAuth2AuthenticationProcessingFilter.java

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {

    final boolean debug = logger.isDebugEnabled();
    final HttpServletRequest request = (HttpServletRequest) req;
    final HttpServletResponse response = (HttpServletResponse) res;

    try {//from  w w  w .j a  v  a  2 s . c o  m

        Authentication authentication = tokenExtractor.extract(request);

        if (authentication == null) {
            if (stateless && isAuthenticated()) {
                if (debug) {
                    logger.debug("Clearing security context.");
                }
                SecurityContextHolder.clearContext();
            }
            if (debug) {
                logger.debug("No token in request, will continue chain.");
            }
        } else {
            request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE, authentication.getPrincipal());
            if (authentication instanceof AbstractAuthenticationToken) {
                AbstractAuthenticationToken needsDetails = (AbstractAuthenticationToken) authentication;
                needsDetails.setDetails(authenticationDetailsSource.buildDetails(request));
            }
            User user = userRepository.findByAccessToken(authentication.getName());
            UsernamePasswordAuthenticationToken authenticate = new UsernamePasswordAuthenticationToken(
                    user.getProviderUserId(), user.getAccessToken(), user.getAuthorities());
            authenticate.setDetails(authentication.getDetails());

            SecurityContextHolder.getContext().setAuthentication(authenticate);

        }
    } catch (OAuth2Exception failed) {
        SecurityContextHolder.clearContext();

        if (debug) {
            logger.debug("Authentication request failed: " + failed);
        }
        eventPublisher.publishAuthenticationFailure(new BadCredentialsException(failed.getMessage(), failed),
                new PreAuthenticatedAuthenticationToken("access-token", "N/A"));

        authenticationEntryPoint.commence(request, response,
                new InsufficientAuthenticationException(failed.getMessage(), failed));

        return;
    }

    chain.doFilter(request, response);
}

From source file:com.telefonica.euro_iaas.sdc.rest.auth.OpenStackAuthenticationProvider.java

/**
 * Authentication fiware.//from   w  ww .j av  a2s. c o m
 * 
 * @param token
 *            the token
 * @param tenantId
 *            the tenantId
 * @return the open stack user
 */
@SuppressWarnings("deprecation")
private PaasManagerUser authenticationFiware(String token, String tenantId) {

    String keystoneURL = systemPropertiesProvider.getProperty(SystemPropertiesProvider.KEYSTONE_URL);

    String adminUser = systemPropertiesProvider.getProperty(SystemPropertiesProvider.KEYSTONE_USER);

    String adminPass = systemPropertiesProvider.getProperty(SystemPropertiesProvider.KEYSTONE_PASS);

    String adminTenant = systemPropertiesProvider.getProperty(SystemPropertiesProvider.KEYSTONE_TENANT);

    String thresholdString = systemPropertiesProvider
            .getProperty(SystemPropertiesProvider.VALIDATION_TIME_THRESHOLD);

    DefaultHttpClient httpClient = new DefaultHttpClient();

    if (oSAuthToken == null) {
        ArrayList<Object> params = new ArrayList();

        Long threshold = Long.parseLong(thresholdString);

        params.add(keystoneURL);
        params.add(adminTenant);
        params.add(adminUser);
        params.add(adminPass);
        params.add(httpClient);
        params.add(threshold);

        oSAuthToken = new OpenStackAuthenticationToken(params);
    }

    String[] credential = oSAuthToken.getCredentials();

    log.debug("Keystone URL : " + keystoneURL);
    log.debug("adminToken : " + credential[0]);

    Client client = Client.create();
    WebResource webResource = client.resource(keystoneURL);
    try {

        // Validate user's token
        AuthenticateResponse responseAuth = webResource.path("tokens").path(token)
                .header("Accept", "application/xml").header("X-Auth-Token", credential[0])
                .get(AuthenticateResponse.class);

        if (!tenantId.equals(responseAuth.getToken().getTenant().getId())) {
            throw new AuthenticationServiceException("Token " + responseAuth.getToken().getTenant().getId()
                    + " not valid for the tenantId provided:" + tenantId);
        }

        Set<GrantedAuthority> authsSet = new HashSet<GrantedAuthority>();

        if (responseAuth.getUser().getRoles() != null) {
            for (Role role : responseAuth.getUser().getRoles().getRole()) {
                authsSet.add(new GrantedAuthorityImpl(role.getName()));
            }
        }

        PaasManagerUser user = new PaasManagerUser(
                responseAuth.getUser().getOtherAttributes().get(new QName("username")), token, authsSet);

        user.setTenantId(tenantId);
        user.setTenantName(responseAuth.getToken().getTenant().getName());
        user.setToken(token);
        return user;

    } catch (UniformInterfaceException e) {
        // this.OSAuthToken.close();
        // this.OSAuthToken = null;

        log.error("response status:" + e.getResponse().getStatus());

        if ((e.getResponse().getStatus() == CODE_401) || (e.getResponse().getStatus() == CODE_403)
                || (e.getResponse().getStatus() == CODE_404)) {
            throw new BadCredentialsException("Token not valid", e);
        }

        throw new AuthenticationServiceException("Token not valid", e);
    } catch (Exception e) {
        // this.OSAuthToken.close();
        // this.OSAuthToken = null;

        throw new AuthenticationServiceException("unknown problem", e);
    }
}

From source file:com.hp.autonomy.hod.sso.HodAuthenticationProvider.java

/**
 * Authenticates the given authentication
 * @param authentication The authentication to authenticate. This should be a HodTokenAuthentication
 * @return A HodAuthentication based on the given HodTokenAuthentication
 * @throws AuthenticationException if authentication fails
 *//*from  w  w w. j a v  a2  s  .c  o  m*/
@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
    final AuthenticationToken<EntityType.Combined, TokenType.Simple> combinedToken = ((HodTokenAuthentication) authentication)
            .getCredentials();
    final CombinedTokenInformation combinedTokenInformation;

    try {
        combinedTokenInformation = authenticationService.getCombinedTokenInformation(combinedToken);
    } catch (final HodErrorException e) {
        if (HodErrorCode.AUTHENTICATION_FAILED.equals(e.getErrorCode())) {
            throw new BadCredentialsException("HOD authentication failed", e);
        } else {
            throw new AuthenticationServiceException("HOD returned an error while authenticating", e);
        }
    }

    final UUID unboundAuthenticationUuid;

    try {
        unboundAuthenticationUuid = unboundTokenService.getAuthenticationUuid();
    } catch (final HodErrorException e) {
        throw new AuthenticationServiceException("HOD returned an error while authenticating", e);
    }

    if (!unboundAuthenticationUuid
            .equals(combinedTokenInformation.getApplication().getAuthentication().getUuid())) {
        // The provided combined token was not generated with our unbound token
        throw new BadCredentialsException("Invalid combined token");
    }

    final TokenProxy<EntityType.Combined, TokenType.Simple> combinedTokenProxy;

    try {
        combinedTokenProxy = tokenRepository.insert(combinedToken);
    } catch (final IOException e) {
        throw new AuthenticationServiceException("An error occurred while authenticating", e);
    }

    Map<String, Serializable> metadata = new HashMap<>();
    String name = null;

    final ResourceIdentifier userStore = combinedTokenInformation.getUserStore().getIdentifier();
    final UUID userUuid = combinedTokenInformation.getUser().getUuid();

    if (metadataTypes != null) {
        try {
            metadata = userStoreUsersService.getUserMetadata(combinedTokenProxy, userStore, userUuid,
                    metadataTypes);

            if (hodUsernameResolver != null) {
                name = hodUsernameResolver.resolve(metadata);
            }
        } catch (final HodErrorException e) {
            throw new AuthenticationServiceException("HOD returned an error while authenticating", e);
        }
    }

    String securityInfo = null;

    if (securityInfoRetriever != null) {
        try {
            securityInfo = securityInfoRetriever.getSecurityInfo(combinedTokenInformation.getUser());
        } catch (final Exception e) {
            throw new AuthenticationServiceException("There was an error while authenticating", e);
        }
        if (securityInfo == null) {
            throw new AuthenticationServiceException("There was an error while authenticating");
        }
    }

    final HodAuthenticationPrincipal principal = new HodAuthenticationPrincipal(combinedTokenInformation, name,
            metadata, securityInfo);
    final ResourceIdentifier applicationIdentifier = combinedTokenInformation.getApplication().getIdentifier();

    // Resolve application granted authorities, adding an authority representing the HOD application
    final Collection<GrantedAuthority> grantedAuthorities = ImmutableSet.<GrantedAuthority>builder()
            .addAll(authoritiesResolver.resolveAuthorities(combinedTokenProxy, combinedTokenInformation))
            .add(new HodApplicationGrantedAuthority(applicationIdentifier)).build();

    return new HodAuthentication<>(combinedTokenProxy, grantedAuthorities, principal);
}

From source file:org.cloudfoundry.identity.uaa.authentication.manager.AutologinAuthenticationManager.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    if (!(authentication instanceof AuthzAuthenticationRequest)) {
        return null;
    }//  w w  w.j  av a 2 s .  c  o m

    AuthzAuthenticationRequest request = (AuthzAuthenticationRequest) authentication;
    Map<String, String> info = request.getInfo();
    String code = info.get("code");

    ExpiringCode expiringCode = doRetrieveCode(code);
    Map<String, String> codeData = null;
    try {
        if (expiringCode == null) {
            logger.debug("Autologin code has expired");
            throw new InvalidCodeException("expired_code", "Expired code", 422);
        }
        codeData = JsonUtils.readValue(expiringCode.getData(), new TypeReference<Map<String, String>>() {
        });
        if (!isAutologinCode(expiringCode.getIntent(), codeData.get("action"))) {
            logger.debug("Code is not meant for autologin");
            throw new InvalidCodeException("invalid_code", "Not an autologin code", 422);
        }
    } catch (JsonUtils.JsonUtilException x) {
        throw new BadCredentialsException("JsonConversion error", x);
    }

    String userId = codeData.get("user_id");
    String clientId = codeData.get(OAuth2Utils.CLIENT_ID);

    if (clientId == null) {
        throw new BadCredentialsException("Cannot redeem provided code for user, client id missing");
    }

    try {
        clientDetailsService.loadClientByClientId(clientId);
    } catch (NoSuchClientException x) {
        throw new BadCredentialsException("Cannot redeem provided code for user, client is missing");
    }

    UaaUser user = null;

    try {
        user = userDatabase.retrieveUserById(userId);
    } catch (UsernameNotFoundException e) {
        throw new BadCredentialsException("Cannot redeem provided code for user, user is missing");
    }

    UaaAuthenticationDetails details = (UaaAuthenticationDetails) authentication.getDetails();
    if (!clientId.equals(details.getClientId())) {
        throw new BadCredentialsException("Cannot redeem provided code for user, client mismatch");
    }

    UaaPrincipal principal = new UaaPrincipal(user);

    return new UaaAuthentication(principal, UaaAuthority.USER_AUTHORITIES,
            (UaaAuthenticationDetails) authentication.getDetails());
}

From source file:org.cloudfoundry.identity.uaa.ldap.PasswordComparisonAuthenticator.java

public DirContextOperations localCompareAuthenticate(DirContextOperations user, String password) {
    boolean match = false;
    try {/*from   w  ww.j av  a  2  s. c  o  m*/
        Attributes attributes = user.getAttributes();
        Attribute attr = attributes.get(getPasswordAttributeName());
        if (attr.size() == 0) {
            throw new AuthenticationCredentialsNotFoundException(
                    "Missing " + getPasswordAttributeName() + " attribute.");
        }
        for (int i = 0; (attr != null) && (!match) && (i < attr.size()); i++) {
            Object valObject = attr.get(i);
            if (valObject != null && valObject instanceof byte[]) {
                if (passwordEncoder instanceof DynamicPasswordComparator) {
                    byte[] received = password.getBytes();
                    byte[] stored = (byte[]) valObject;
                    match = ((DynamicPasswordComparator) passwordEncoder).comparePasswords(received, stored);
                } else {
                    String encodedPassword = passwordEncoder.encodePassword(password, null);
                    byte[] passwordBytes = Utf8.encode(encodedPassword);
                    match = Arrays.equals(passwordBytes, (byte[]) valObject);
                }
            }
        }
    } catch (NamingException e) {
        throw new BadCredentialsException("Bad credentials", e);
    }
    if (!match)
        throw new BadCredentialsException("Bad credentials");
    return user;
}

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

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    if (!(authentication instanceof AuthzAuthenticationRequest)) {
        return null;
    }/*from w  w  w. j  ava 2 s  . com*/

    AuthzAuthenticationRequest request = (AuthzAuthenticationRequest) authentication;
    Map<String, String> info = request.getInfo();
    String code = info.get("code");

    ExpiringCode ec = doRetrieveCode(code);
    SocialClientUserDetails user = null;
    try {
        if (ec != null) {
            user = new ObjectMapper().readValue(ec.getData(), SocialClientUserDetails.class);
        }
    } catch (IOException x) {
        throw new BadCredentialsException("JsonConversion error", x);
    }

    if (user == null) {
        throw new BadCredentialsException("Cannot redeem provided code for user");
    }

    // ensure that we stored clientId
    String clientId = null;
    String origin = null;
    String userId = null;
    Object principal = user.getUsername();
    if (user.getDetails() instanceof String) {
        clientId = (String) user.getDetails();
    } else if (user.getDetails() instanceof Map) {
        Map<String, String> map = (Map<String, String>) user.getDetails();
        clientId = map.get("client_id");
        origin = map.get(Origin.ORIGIN);
        userId = map.get("user_id");
        principal = new UaaPrincipal(userId, user.getUsername(), null, origin, null);
    }
    if (clientId == null) {
        throw new BadCredentialsException("Cannot redeem provided code for user, client id missing");
    }

    // validate the client Id
    if (!(authentication.getDetails() instanceof UaaAuthenticationDetails)) {
        throw new BadCredentialsException("Cannot redeem provided code for user, auth details missing");
    }

    UaaAuthenticationDetails details = (UaaAuthenticationDetails) authentication.getDetails();
    if (!clientId.equals(details.getClientId())) {
        throw new BadCredentialsException("Cannot redeem provided code for user, client mismatch");
    }

    UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(principal, null,
            user.getAuthorities());
    result.setDetails(authentication.getDetails());
    return result;

}

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

/**
 * Populates the Spring Security context with a
 * {@link UsernamePasswordAuthenticationToken} referring to the client
 * that authenticates using the basic authorization header.
 *///from   w ww  .j  a  v  a 2s  .  com
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest servletRequest = (HttpServletRequest) request;
    String header = servletRequest.getHeader("Authorization");
    if (header == null || !header.startsWith("Basic ")) {
        chain.doFilter(request, response);
        return;
    }

    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization", header);

    try {

        ResponseEntity<BaseClientDetails> result = restTemplate.exchange(clientInfoUrl, HttpMethod.GET,
                new HttpEntity<Void>(headers), BaseClientDetails.class);

        ClientDetails client = result.getBody();
        String clientId = client.getClientId();
        validateClient(client);

        Authentication authResult = new UsernamePasswordAuthenticationToken(clientId, "<NONE>",
                client.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authResult);

    } catch (RuntimeException e) {
        logger.debug("Authentication failed");
        authenticationEntryPoint.commence(servletRequest, (HttpServletResponse) response,
                new BadCredentialsException("Could not authenticate", e));
        return;
    }

    chain.doFilter(request, response);

}

From source file:org.fao.geonet.kernel.security.ecas.ECasAuthenticationProvider.java

private CasAuthenticationToken authenticateNow(final Authentication authentication)
        throws AuthenticationException {
    try {// w  ww.j  a  v  a 2  s.c  o m
        final Assertion assertion = this.ticketValidator.validate(authentication.getCredentials().toString(),
                getServiceUrl(authentication));
        final UserDetails userDetails = loadUserByAssertion(assertion);
        userDetailsChecker.check(userDetails);
        return new CasAuthenticationToken(this.key, userDetails, authentication.getCredentials(),
                authoritiesMapper.mapAuthorities(userDetails.getAuthorities()), userDetails, assertion);
    } catch (final TicketValidationException e) {
        throw new BadCredentialsException(e.getMessage(), e);
    }
}