Example usage for org.apache.http.auth InvalidCredentialsException InvalidCredentialsException

List of usage examples for org.apache.http.auth InvalidCredentialsException InvalidCredentialsException

Introduction

In this page you can find the example usage for org.apache.http.auth InvalidCredentialsException InvalidCredentialsException.

Prototype

public InvalidCredentialsException(final String message) 

Source Link

Document

Creates a new InvalidCredentialsException with the specified message.

Usage

From source file:org.Cherry.Modules.Security.Middleware.UserRepository.java

public InvalidCredentialsException authenticate(final User criteria) {
    final User found = find(criteria);

    if (null == found)
        return new InvalidCredentialsException("Non existing identity [" + criteria.getName() + "]!");

    final Boolean paroleMatch = getCryptoService().checkParole(criteria.getParole(), found.getParole());// found.getParole().equals(criteria.getParole())

    if (!paroleMatch)
        return new InvalidCredentialsException("Parole failure for identity [" + criteria.getName() + "]!");

    return null;//from  w w w  .jav a  2 s  . c  o m
}

From source file:com.androidquery.test.NTLMScheme.java

public Header authenticate(final Credentials credentials, final HttpRequest request)
        throws AuthenticationException {
    NTCredentials ntcredentials = null;/*  www.j a  v a  2s.c  o m*/
    try {
        ntcredentials = (NTCredentials) credentials;
    } catch (ClassCastException e) {
        throw new InvalidCredentialsException(
                "Credentials cannot be used for NTLM authentication: " + credentials.getClass().getName());
    }
    String response = null;
    if (this.state == State.CHALLENGE_RECEIVED || this.state == State.FAILED) {
        response = this.engine.generateType1Msg(ntcredentials.getDomain(), ntcredentials.getWorkstation());
        this.state = State.MSG_TYPE1_GENERATED;
    } else if (this.state == State.MSG_TYPE2_RECEVIED) {
        response = this.engine.generateType3Msg(ntcredentials.getUserName(), ntcredentials.getPassword(),
                ntcredentials.getDomain(), ntcredentials.getWorkstation(), this.challenge);
        this.state = State.MSG_TYPE3_GENERATED;
    } else {
        throw new AuthenticationException("Unexpected state: " + this.state);
    }
    CharArrayBuffer buffer = new CharArrayBuffer(32);
    if (isProxy()) {
        buffer.append(AUTH.PROXY_AUTH_RESP);
    } else {
        buffer.append(AUTH.WWW_AUTH_RESP);
    }
    buffer.append(": NTLM ");
    buffer.append(response);
    return new BufferedHeader(buffer);
}

From source file:com.ibm.team.build.internal.hjplugin.util.HttpUtils.java

/**
 * Perform GET request against an RTC server
 * @param serverURI The RTC server//from   w  ww.j av a 2s . c om
 * @param uri The relative URI for the GET. It is expected it is already encoded if necessary.
 * @param userId The userId to authenticate as
 * @param password The password to authenticate with
 * @param timeout The timeout period for the connection (in seconds)
 * @param httpContext The context from the login if cycle is being managed by the caller
 * Otherwise <code>null</code> and this call will handle the login.
 * @param listener The listener to report errors to. May be 
 * <code>null</code>
 * @return Result of the GET (JSON response)
 * @throws IOException Thrown if things go wrong
 * @throws InvalidCredentialsException
 * @throws GeneralSecurityException 
 */
public static GetResult performGet(String serverURI, String uri, String userId, String password, int timeout,
        HttpClientContext httpContext, TaskListener listener)
        throws IOException, InvalidCredentialsException, GeneralSecurityException {

    CloseableHttpClient httpClient = getClient();
    String fullURI = getFullURI(serverURI, uri);
    HttpGet request = getGET(fullURI, timeout);
    if (httpContext == null) {
        httpContext = createHttpContext();
    }

    LOGGER.finer("GET: " + request.getURI()); //$NON-NLS-1$
    CloseableHttpResponse response = httpClient.execute(request, httpContext);
    try {
        // based on the response do any authentication. If authentication requires
        // the request to be performed again (i.e. Basic auth) re-issue request
        response = authenticateIfRequired(response, httpClient, httpContext, serverURI, userId, password,
                timeout, listener);
        if (response == null) {
            // retry get
            request = getGET(fullURI, timeout);
            response = httpClient.execute(request, httpContext);
        }
        int statusCode = response.getStatusLine().getStatusCode();

        if (statusCode == 200) {
            InputStreamReader inputStream = new InputStreamReader(response.getEntity().getContent(), UTF_8);
            try {
                String responseContent = IOUtils.toString(inputStream);
                GetResult result = new GetResult(httpContext, JSONSerializer.toJSON(responseContent));
                return result;
            } finally {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    LOGGER.finer("Failed to close the result input stream for request: " + fullURI); //$NON-NLS-1$
                }
            }
        } else if (statusCode == 401) {
            // if still un-authorized, then there is a good chance the basic credentials are bad.
            throw new InvalidCredentialsException(Messages.HttpUtils_authentication_failed(userId, serverURI));

        } else {
            // capture details about the error
            LOGGER.finer(Messages.HttpUtils_GET_failed(fullURI, statusCode));
            if (listener != null) {
                listener.fatalError(Messages.HttpUtils_GET_failed(fullURI, statusCode));
            }
            throw logError(fullURI, response, Messages.HttpUtils_GET_failed(fullURI, statusCode));
        }
    } finally {
        closeResponse(response);
    }
}

From source file:com.ibm.team.build.internal.hjplugin.util.HttpUtils.java

/**
 * Perform PUT request against an RTC server
 * @param serverURI The RTC server//  w  ww .j a va2  s .  c o  m
 * @param uri The relative URI for the PUT. It is expected that it is already encoded if necessary.
 * @param userId The userId to authenticate as
 * @param password The password to authenticate with
 * @param timeout The timeout period for the connection (in seconds)
 * @param json The JSON object to put to the RTC server
 * @param httpContext The context from the login if cycle is being managed by the caller
 * Otherwise <code>null</code> and this call will handle the login.
 * @param listener The listener to report errors to.
 * May be <code>null</code> if there is no listener.
 * @return The HttpContext for the request. May be reused in subsequent requests
 * for the same user
 * @throws IOException Thrown if things go wrong
 * @throws InvalidCredentialsException
 * @throws GeneralSecurityException 
 */
public static HttpClientContext performPut(String serverURI, String uri, String userId, String password,
        int timeout, final JSONObject json, HttpClientContext httpContext, TaskListener listener)
        throws IOException, InvalidCredentialsException, GeneralSecurityException {

    CloseableHttpClient httpClient = getClient();
    // How to fill the request body (Clone doesn't work)
    ContentProducer cp = new ContentProducer() {
        public void writeTo(OutputStream outstream) throws IOException {
            Writer writer = new OutputStreamWriter(outstream, UTF_8);
            json.write(writer);
            writer.flush();
        }
    };
    HttpEntity entity = new EntityTemplate(cp);
    String fullURI = getFullURI(serverURI, uri);
    HttpPut put = getPUT(fullURI, timeout);
    put.setEntity(entity);

    if (httpContext == null) {
        httpContext = createHttpContext();
    }

    LOGGER.finer("PUT: " + put.getURI()); //$NON-NLS-1$
    CloseableHttpResponse response = httpClient.execute(put, httpContext);
    try {
        // based on the response do any authentication. If authentication requires
        // the request to be performed again (i.e. Basic auth) re-issue request
        response = authenticateIfRequired(response, httpClient, httpContext, serverURI, userId, password,
                timeout, listener);

        // retry put request if we have to do authentication
        if (response == null) {
            put = getPUT(fullURI, timeout);
            put.setEntity(entity);
            response = httpClient.execute(put, httpContext);
        }

        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == 401) {
            // It is an unusual case to get here (in our current work flow) because it means
            // the user has become unauthenticated since the previous request 
            // (i.e. the get of the value about to put back)
            throw new InvalidCredentialsException(Messages.HttpUtils_authentication_failed(userId, serverURI));

        } else {
            int responseClass = statusCode / 100;
            if (responseClass != 2) {
                if (listener != null) {
                    listener.fatalError(Messages.HttpUtils_PUT_failed(fullURI, statusCode));
                }

                throw logError(fullURI, response, Messages.HttpUtils_PUT_failed(fullURI, statusCode));
            }
            return httpContext;
        }
    } finally {
        closeResponse(response);
    }
}

From source file:main.DOORS_Service.java

private static void validateTokens(OslcOAuthClient client, String redirect, String user, String password,
        String authURL) throws Exception {

    HttpGet request2 = new HttpGet(redirect);
    HttpClientParams.setRedirecting(request2.getParams(), false);
    HttpResponse response = client.getHttpClient().execute(request2);
    EntityUtils.consume(response.getEntity());

    // Get the location
    Header location = response.getFirstHeader("Location");
    HttpGet request3 = new HttpGet(location.getValue());
    HttpClientParams.setRedirecting(request3.getParams(), false);
    response = client.getHttpClient().execute(request3);
    EntityUtils.consume(response.getEntity());

    //POST to login form
    // The server requires an authentication: Create the login form
    // Following line should be like : "https://server:port/dwa/j_acegi_security_check"
    HttpPost formPost = new HttpPost(authURL);
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("j_username", user));
    nvps.add(new BasicNameValuePair("j_password", password));
    formPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

    HttpResponse formResponse = client.getHttpClient().execute(formPost);
    EntityUtils.consume(formResponse.getEntity());

    location = formResponse.getFirstHeader("Location");
    //Third GET/* ww w.j a v  a  2 s.c  om*/
    HttpGet request4 = new HttpGet(location.getValue());
    HttpClientParams.setRedirecting(request4.getParams(), false);
    response = client.getHttpClient().execute(request4);
    EntityUtils.consume(response.getEntity());

    location = response.getFirstHeader("Location");
    Map<String, String> oAuthMap = getQueryMap(location.getValue());
    String oauthToken = oAuthMap.get("oauth_token");
    String oauthverifier = oAuthMap.get("oauth_verifier");

    // The server requires an authentication: Create the login form
    HttpPost formPost2 = new HttpPost(location.getValue());
    formPost2.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
    HttpParams params = new BasicHttpParams();
    params.setParameter("oauth_token", oauthToken);
    params.setParameter("oauth_verifier", oauthverifier);
    params.setParameter("authorize", "true");
    formPost2.setParams(params);

    formResponse = client.getHttpClient().execute(formPost2);
    EntityUtils.consume(formResponse.getEntity());

    Header header = formResponse.getFirstHeader("Content-Length");
    if ((header != null) && (!("0".equals(header.getValue())))) {
        // The login failed
        throw new InvalidCredentialsException("Authentication failed");
    } else {
        // The login succeed
        // Step (3): Request again the protected resource
        EntityUtils.consume(formResponse.getEntity());
    }
}

From source file:com.ibm.team.build.internal.hjplugin.util.HttpUtils.java

/**
 * Check the response for a delete (or it could be a get if we were following
 * redirects & posted the form). Idea is to see if its an auth failure or
 * something really serious (not found isn't serious, just means already deleted).
 * @param response The response//www .j  a va  2 s  . c  o  m
 * @param fullURI The full uri that was used for the request.
 * @param serverURI The RTC Server portion of the uri
 * @param userId The user id on behalf of whom the request was made
 * @param listener A listener to notify of issues.
 * @throws InvalidCredentialsException Thrown if the authentication failed.
 * @throws IOException Thrown if a serious error occurred.
 */
private static void checkDeleteResponse(CloseableHttpResponse response, String fullURI, String serverURI,
        String userId, TaskListener listener) throws InvalidCredentialsException, IOException {
    int statusCode;
    statusCode = response.getStatusLine().getStatusCode();
    if (statusCode == 401) {
        // the user is unauthenticated
        throw new InvalidCredentialsException(Messages.HttpUtils_authentication_failed(userId, serverURI));

    } else if (statusCode == 404) {
        // this is ok, build result already deleted

    } else {
        int responseClass = statusCode / 100;
        if (responseClass != 2) {
            if (listener != null) {
                listener.fatalError(Messages.HttpUtils_DELETE_failed(fullURI, statusCode));
            }

            throw logError(fullURI, response, Messages.HttpUtils_DELETE_failed(fullURI, statusCode));
        }
    }
}

From source file:org.eclipse.lyo.client.oslc.samples.DoorsOauthSample.java

private static void validateTokens(OslcOAuthClient client, String redirect, String user, String password,
        String authURL) throws Exception {

    HttpGet request2 = new HttpGet(redirect);
    HttpClientParams.setRedirecting(request2.getParams(), false);
    HttpResponse response = client.getHttpClient().execute(request2);
    EntityUtils.consume(response.getEntity());

    // Get the location
    Header location = response.getFirstHeader("Location");
    HttpGet request3 = new HttpGet(location.getValue());
    HttpClientParams.setRedirecting(request3.getParams(), false);
    response = client.getHttpClient().execute(request3);
    EntityUtils.consume(response.getEntity());

    //POST to login form
    // The server requires an authentication: Create the login form
    // Following line should be like : "https://server:port/dwa/j_acegi_security_check"
    HttpPost formPost = new HttpPost(authURL);
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("j_username", user));
    nvps.add(new BasicNameValuePair("j_password", password));
    formPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

    HttpResponse formResponse = client.getHttpClient().execute(formPost);
    EntityUtils.consume(formResponse.getEntity());

    location = formResponse.getFirstHeader("Location");
    //Third GET/*from  ww w  .  j  av a 2 s. c  om*/
    HttpGet request4 = new HttpGet(location.getValue());
    HttpClientParams.setRedirecting(request4.getParams(), false);
    response = client.getHttpClient().execute(request4);
    EntityUtils.consume(response.getEntity());

    Map<String, String> oAuthMap = getQueryMap(location.getValue());
    String oauthToken = oAuthMap.get("oauth_token");
    String oauthverifier = oAuthMap.get("oauth_verifier");

    // The server requires an authentication: Create the login form
    HttpPost formPost2 = new HttpPost(authURL);
    formPost2.getParams().setParameter("oauth_token", oauthToken);
    formPost2.getParams().setParameter("oauth_verifier", oauthverifier);
    formPost2.getParams().setParameter("authorize", "true");
    formPost2.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");

    formResponse = client.getHttpClient().execute(formPost2);
    EntityUtils.consume(formResponse.getEntity());

    Header header = formResponse.getFirstHeader("Content-Length");
    if ((header != null) && (!("0".equals(header.getValue())))) {
        // The login failed
        throw new InvalidCredentialsException("Authentication failed");
    } else {
        // The login succeed
        // Step (3): Request again the protected resource
        EntityUtils.consume(formResponse.getEntity());
    }
}

From source file:com.ibm.team.build.internal.hjplugin.util.HttpUtils.java

/**
 * Only used to test connection.//from w ww  .j  a  va  2s . co m
 * @param serverURI The RTC server
 * @param userId The userId to authenticate as
 * @param password The password to authenticate with
 * @param timeout The timeout period for the connection (in seconds)
 * @return The HttpContext to be used in a series of requests (so we only need to
 * login once).
 * @throws IOException Thrown if things go wrong
 * @throws InvalidCredentialsException if authentication fails
 * @throws GeneralSecurityException 
 */
public static void validateCredentials(String serverURI, String userId, String password, int timeout)
        throws IOException, GeneralSecurityException, InvalidCredentialsException {
    // We can't directly do a post because we need a JSession id cookie.
    // Instead attempt to do a get and then verify the credentials when we need to do
    // the form based auth. Don't bother to re-issue the get though. We just want
    // to know if the Login works

    CloseableHttpClient httpClient = getClient();
    HttpGet request = getGET(serverURI, timeout);
    HttpClientContext httpContext = createHttpContext();

    LOGGER.finer("GET: " + request.getURI()); //$NON-NLS-1$
    CloseableHttpResponse response = httpClient.execute(request, httpContext);
    try {
        response = authenticateIfRequired(response, httpClient, httpContext, serverURI, userId, password,
                timeout, null);
        if (response == null) {
            // retry get - if doing form based auth, not required
            // but if its basic auth then we do need to re-issue since basic just updates the context
            request = getGET(serverURI, timeout);
            response = httpClient.execute(request, httpContext);
            if (response.getStatusLine().getStatusCode() == 401) {
                // still not authorized
                throw new InvalidCredentialsException(
                        Messages.HttpUtils_authentication_failed(userId, serverURI));
            }
        }

    } finally {
        closeResponse(response);
    }
}

From source file:com.ibm.team.build.internal.hjplugin.util.HttpUtils.java

/**
 * Post a login form to the server when authentication was required by the previous request
 * @param httpClient The httpClient to use for the requests
 * @param httpContext httpContext with it's own cookie store for use with the singleton HTTP_CLIENT
 * Not <code>null</code>/*from  w ww  .j av a2  s.c o  m*/
 * @param serverURI The RTC server
 * @param userId The userId to authenticate as
 * @param password The password to authenticate with
 * @param timeout The timeout period for the connection (in seconds)
 * @param listener The listener to report errors to. May be 
 * <code>null</code>
 * @throws IOException Thrown if things go wrong
 * @throws InvalidCredentialsException if authentication fails
 */
private static CloseableHttpResponse handleFormBasedChallenge(CloseableHttpClient httpClient,
        HttpClientContext httpContext, String serverURI, String userId, String password, int timeout,
        TaskListener listener) throws IOException, InvalidCredentialsException {

    // The server requires an authentication: Create the login form
    String fullURI = getFullURI(serverURI, "j_security_check");
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("j_username", userId)); //$NON-NLS-1$
    nvps.add(new BasicNameValuePair("j_password", password)); //$NON-NLS-1$

    HttpPost formPost = getPOST(fullURI, timeout); //$NON-NLS-1$
    formPost.setEntity(new UrlEncodedFormEntity(nvps, UTF_8));

    // The client submits the login form
    LOGGER.finer("POST: " + formPost.getURI()); //$NON-NLS-1$
    CloseableHttpResponse formResponse = httpClient.execute(formPost, httpContext);
    int statusCode = formResponse.getStatusLine().getStatusCode();
    Header header = formResponse.getFirstHeader(FORM_AUTHREQUIRED_HEADER);

    // check to see if the authentication was successful
    if (statusCode / 100 == 2 && (header != null) && (AUTHFAILED_HEADER_VALUE.equals(header.getValue()))) {
        closeResponse(formResponse);
        throw new InvalidCredentialsException(Messages.HttpUtils_authentication_failed(userId, serverURI));
    }
    return formResponse;
}

From source file:org.apache.http.impl.auth.win.WindowsNegotiateScheme.java

@Override
public Header authenticate(final Credentials credentials, final HttpRequest request, final HttpContext context)
        throws AuthenticationException {

    final String response;
    if (clientCred == null) {
        // ?? We don't use the credentials, should we allow anything?
        if (!(credentials instanceof CurrentWindowsCredentials)) {
            throw new InvalidCredentialsException("Credentials cannot be used for " + getSchemeName()
                    + " authentication: " + credentials.getClass().getName());
        }/*from  w  ww .j  ava  2s.c o m*/

        // client credentials handle
        try {
            final String username = CurrentWindowsCredentials.getCurrentUsername();
            final TimeStamp lifetime = new TimeStamp();

            clientCred = new CredHandle();
            final int rc = Secur32.INSTANCE.AcquireCredentialsHandle(username, scheme,
                    Sspi.SECPKG_CRED_OUTBOUND, null, null, null, null, clientCred, lifetime);

            if (WinError.SEC_E_OK != rc) {
                throw new Win32Exception(rc);
            }

            response = getToken(null, null, username);
        } catch (Throwable t) {
            dispose();
            throw new AuthenticationException("Authentication Failed", t);
        }
    } else if (this.challenge == null || this.challenge.length() == 0) {
        dispose();
        throw new AuthenticationException("Authentication Failed");
    } else {
        try {
            final byte[] continueTokenBytes = Base64.decodeBase64(this.challenge);
            final SecBufferDesc continueTokenBuffer = new SecBufferDesc(Sspi.SECBUFFER_TOKEN,
                    continueTokenBytes);
            response = getToken(this.sppicontext, continueTokenBuffer, "localhost");
        } catch (Throwable t) {
            dispose();
            throw new AuthenticationException("Authentication Failed", t);
        }
    }

    final CharArrayBuffer buffer = new CharArrayBuffer(scheme.length() + 30);
    if (isProxy()) {
        buffer.append(AUTH.PROXY_AUTH_RESP);
    } else {
        buffer.append(AUTH.WWW_AUTH_RESP);
    }
    buffer.append(": ");
    buffer.append(scheme); // NTLM or Negotiate
    buffer.append(" ");
    buffer.append(response);
    return new BufferedHeader(buffer);
}