You are viewing a plain text version of this content. The canonical link for it is here.
Posted to httpclient-users@hc.apache.org by Guri Bhai <gu...@gmail.com> on 2011/03/24 10:22:40 UTC

RE: HTTPS redirects and then basic auth fails


If you were able to solve this, can you help how? i am in a similar
situation. 



Mudnal, Fayaz K wrote:
> 
> I set the auth realm to AuthScope.ANY, but this did not work either:
> httpstate.setCredentials(AuthScope.ANY, credentials);
> 
> Fayaz
> 
> -----Original Message-----
> From: Mudnal, Fayaz K [mailto:fmudnal@visa.com] 
> Sent: Tuesday, October 12, 2010 4:19 PM
> To: httpclient-users@hc.apache.org
> Subject: HTTPS redirects and then basic auth fails
> 
> Hi
> I am trying to upload a file to a https site. The site redirects 3 times
> and then login fails with a 401 error. I am using HttpClient 3.0. The
> server folks said they could not see the credentials on their side. I
> would greatly appreciate any help. Here is the code:
> 
>        String header = "multipart/form-data";
>         PostMethod method = null;
> 
>         try {
>             HttpClient client = new HttpClient();
>             HostConfiguration hostConfig = client.getHostConfiguration();
>             hostConfig.setHost(new URI(URL, true));
>             LOGGER.debug("Open connection to: " + URL);
>             if (username != null && password != null &&
> username.trim().length() > 0 && password.trim().length() > 0) {
>                 LOGGER.debug("Setting credentials.");
>                 Credentials credentials = new
> UsernamePasswordCredentials(username, password);
>                 AuthScope authScope = new AuthScope(hostConfig.getHost(),
> hostConfig.getPort());
>                 HttpState state = client.getState();
>                 state.setCredentials(authScope, credentials);
>                 LOGGER.debug("Credentials set");
>                 List authPrefs = new ArrayList(3);
>                 authPrefs.add(AuthPolicy.BASIC);
>                 authPrefs.add(AuthPolicy.DIGEST);
>                 authPrefs.add(AuthPolicy.NTLM);
> 
>                
> client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY,
> authPrefs);
>                 client.getParams().setAuthenticationPreemptive(true);
>                 LOGGER.debug("Preemptive Authentication set");
>             }
>             RequestEntity entity = new
> InputStreamRequestEntity(inputStream, "application/upload");
>             method = new PostMethod(URL);
>             method.setRequestEntity(entity);
>             LOGGER.debug("FileInputStream set");
>             method.setRequestHeader("filename", fileName);
>             method.setRequestHeader("Content-Type", header);
>             method.setRequestHeader("Content-Disposition", "form-data");
>             method.setDoAuthentication(true);
>             method.setFollowRedirects( false );
>             LOGGER.debug("Uploading file...");
>             int responseStatusCode = client.executeMethod(hostConfig,
> method);
>             LOGGER.debug("HTTPS ResponseStatusCode=" +
> responseStatusCode);
>             LOGGER.debug(method.getStatusLine());
>             LOGGER.debug(method.getResponseBodyAsString());
> 
>             // Handle redirects
>             int redirResponseStatusCode = 0;
>             if (responseStatusCode == HttpStatus.SC_MOVED_TEMPORARILY ||
>                     responseStatusCode == HttpStatus.SC_MOVED_PERMANENTLY
> ||
>                     responseStatusCode == HttpStatus.SC_SEE_OTHER ||
>                     responseStatusCode ==
> HttpStatus.SC_TEMPORARY_REDIRECT) {
> 
>                 LOGGER.debug("Redirection encountered:" +
> responseStatusCode);
>            // handle a max of 10 redirects
>                 for (int i = 1; i < 11; i++) {
>                     LOGGER.debug("Redirect attempt: " + i);
>                     redirResponseStatusCode = 0;
> 
>                     Header locationHeader =
> method.getResponseHeader("location");
>                     if (locationHeader == null) {
>                       throw new DeliveryException("Redirected without a
> location");
>                     }
>                     String location = locationHeader.getValue();
>                     hostConfig.setHost(new URI(location, true));
>                     method.setURI(new URI(location, true));
> 
>                     if (username != null && password != null &&
> username.trim().length() > 0 && password.trim().length() > 0) {
>                         LOGGER.debug("Setting credentials for redirect.");
>                         Credentials credentials = new
> UsernamePasswordCredentials(username, password);
>                         AuthScope authScope = new
> AuthScope(hostConfig.getHost(), hostConfig.getPort());
>                         HttpState state = client.getState();
>                         state.setCredentials(authScope, credentials);
>                         LOGGER.debug("Credentials set");
>                         List authPrefs = new ArrayList(3);
>                         authPrefs.add(AuthPolicy.BASIC);
>                         authPrefs.add(AuthPolicy.DIGEST);
>                         authPrefs.add(AuthPolicy.NTLM);
> 
>                        
> client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY,
> authPrefs);
>                        
> //client.getState().setAuthenticationPreemptive(true);
>                        
> client.getParams().setAuthenticationPreemptive(true);
>                         LOGGER.debug("Preemptive Authentication set");
>                     }
> 
> 
>                     LOGGER.debug("Redirecting to location:" + location);
>                     redirResponseStatusCode =
> client.executeMethod(hostConfig, method);
> 
> 
>                     LOGGER.debug("HTTPS RedirectResponseStatusCode=" +
> redirResponseStatusCode);
>                     LOGGER.debug(method.getStatusLine());
>                     LOGGER.debug(method.getResponseBodyAsString());
>                     if (redirResponseStatusCode !=
> HttpStatus.SC_MOVED_TEMPORARILY &&
>                             redirResponseStatusCode !=
> HttpStatus.SC_MOVED_PERMANENTLY &&
>                             redirResponseStatusCode !=
> HttpStatus.SC_SEE_OTHER &&
>                             redirResponseStatusCode !=
> HttpStatus.SC_TEMPORARY_REDIRECT)
>                         break;
> 
>                     if (i == 10) {LOGGER.debug("MAX Redirects
> exceeded.");}
>                 }
>             }
>             // Handle redirects
> 
>             if ((responseStatusCode >= 400)||(redirResponseStatusCode >=
> 400)) {
>                 LOGGER.debug("File upload via HTTPS failed.");
>                 throw new DeliveryException("File upload via HTTPS
> failed.");
>             } else
>                 LOGGER.debug("File upload via HTTPS Successful.");
> 
>         } catch (Exception e) {
>             LOGGER.debug("File upload via HTTPS failed.");
>             e.printStackTrace();
>             throw new DeliveryException(e);
>         } finally {
>             method.releaseConnection();
>         }
> 
> Here are the logs:
> [10/12/10 0:52:56:136 GMT] 00000164 SystemOut     O - username:xxxxx
> password:xxxxx
> [10/12/10 0:52:56:137 GMT] 00000164 SystemOut     O - Open connection to:
> https://159.37.35.247/
> [10/12/10 0:52:56:137 GMT] 00000164 SystemOut     O - Setting credentials.
> [10/12/10 0:52:56:138 GMT] 00000164 SystemOut     O - Credentials set
> [10/12/10 0:52:56:139 GMT] 00000164 SystemOut     O - Preemptive
> Authentication set
> [10/12/10 0:52:56:140 GMT] 00000164 SystemOut     O - FileInputStream set
> [10/12/10 0:52:56:141 GMT] 00000164 SystemOut     O - Uploading file...
> [10/12/10 0:52:56:452 GMT] 00000164 HttpMethodDir I
> org.apache.commons.httpclient.HttpMethodDirector isRedirectNeeded Redirect
> requested but followRedirects is disabled
> [10/12/10 0:52:56:459 GMT] 00000164 SystemOut     O - HTTPS
> ResponseStatusCode=302
> [10/12/10 0:52:56:459 GMT] 00000164 SystemOut     O - HTTP/1.1 302 Found
> [10/12/10 0:52:56:459 GMT] 00000164 HttpMethodBas W
> org.apache.commons.httpclient.HttpMethodBase getResponseBody Going to
> buffer response body of large or unknown size. Using
> getResponseBodyAsStream instead is recommended.
> [10/12/10 0:52:56:475 GMT] 00000164 SystemOut     O - <!DOCTYPE HTML
> PUBLIC "-//IETF//DTD HTML 2.0//EN">
> <HTML><HEAD>
> <TITLE>302 Found</TITLE>
> </HEAD><BODY>
> <H1>Found</H1>
> The document has moved 
> https://159.37.35.247:443/?&amp;STCO=1TLOxTpeXQHAAAEqsStY&amp;STCOEND here
> .<P>
> <P>Additionally, a 302 Found
> error was encountered while trying to use an ErrorDocument to handle the
> request.
> </BODY></HTML>
> 
> [10/12/10 0:52:56:475 GMT] 00000164 SystemOut     O - Redirection
> encountered:302
> [10/12/10 0:52:56:476 GMT] 00000164 SystemOut     O - Redirect attempt: 1
> [10/12/10 0:52:56:476 GMT] 00000164 SystemOut     O - Setting credentials
> for redirect.
> [10/12/10 0:52:56:477 GMT] 00000164 SystemOut     O - Credentials set
> [10/12/10 0:52:56:478 GMT] 00000164 SystemOut     O - Preemptive
> Authentication set
> [10/12/10 0:52:56:478 GMT] 00000164 SystemOut     O - Redirecting to
> location:https://159.37.35.247:443/?&STCO=1TLOxTpeXQHAAAEqsStY&STCOEND
> [10/12/10 0:52:56:561 GMT] 00000164 HttpMethodDir I
> org.apache.commons.httpclient.HttpMethodDirector isRedirectNeeded Redirect
> requested but followRedirects is disabled
> [10/12/10 0:52:56:568 GMT] 00000164 SystemOut     O - HTTPS
> RedirectResponseStatusCode=302
> [10/12/10 0:52:56:568 GMT] 00000164 SystemOut     O - HTTP/1.1 302 Found
> [10/12/10 0:52:56:569 GMT] 00000164 HttpMethodBas W
> org.apache.commons.httpclient.HttpMethodBase getResponseBody Going to
> buffer response body of large or unknown size. Using
> getResponseBodyAsStream instead is recommended.
> [10/12/10 0:52:56:584 GMT] 00000164 SystemOut     O - <!DOCTYPE HTML
> PUBLIC "-//IETF//DTD HTML 2.0//EN">
> <HTML><HEAD>
> <TITLE>302 Found</TITLE>
> </HEAD><BODY>
> <H1>Found</H1>
> The document has moved 
> https://159.37.35.247/?&amp;STCO=2TLOxTpeXQHAAAEqsStY&amp;STCOEND here
> .<P>
> <P>Additionally, a 302 Found
> error was encountered while trying to use an ErrorDocument to handle the
> request.
> </BODY></HTML>
> 
> [10/12/10 0:52:56:585 GMT] 00000164 SystemOut     O - Redirect attempt: 2
> [10/12/10 0:52:56:585 GMT] 00000164 SystemOut     O - Setting credentials
> for redirect.
> [10/12/10 0:52:56:586 GMT] 00000164 SystemOut     O - Credentials set
> [10/12/10 0:52:56:586 GMT] 00000164 SystemOut     O - Preemptive
> Authentication set
> [10/12/10 0:52:56:587 GMT] 00000164 SystemOut     O - Redirecting to
> location:https://159.37.35.247/?&STCO=2TLOxTpeXQHAAAEqsStY&STCOEND
> [10/12/10 0:52:56:672 GMT] 00000164 HttpMethodDir I
> org.apache.commons.httpclient.HttpMethodDirector isRedirectNeeded Redirect
> requested but followRedirects is disabled
> [10/12/10 0:52:56:680 GMT] 00000164 SystemOut     O - HTTPS
> RedirectResponseStatusCode=302
> [10/12/10 0:52:56:681 GMT] 00000164 SystemOut     O - HTTP/1.1 302 Found
> [10/12/10 0:52:56:681 GMT] 00000164 HttpMethodBas W
> org.apache.commons.httpclient.HttpMethodBase getResponseBody Going to
> buffer response body of large or unknown size. Using
> getResponseBodyAsStream instead is recommended.
> [10/12/10 0:52:56:696 GMT] 00000164 SystemOut     O - <!DOCTYPE HTML
> PUBLIC "-//IETF//DTD HTML 2.0//EN">
> <HTML><HEAD>
> <TITLE>302 Found</TITLE>
> </HEAD><BODY>
> <H1>Found</H1>
> The document has moved  https://159.37.35.247/ here .<P>
> <P>Additionally, a 302 Found
> error was encountered while trying to use an ErrorDocument to handle the
> request.
> </BODY></HTML>
> 
> [10/12/10 0:52:56:696 GMT] 00000164 SystemOut     O - Redirect attempt: 3
> [10/12/10 0:52:56:697 GMT] 00000164 SystemOut     O - Setting credentials
> for redirect.
> [10/12/10 0:52:56:698 GMT] 00000164 SystemOut     O - Credentials set
> [10/12/10 0:52:56:698 GMT] 00000164 SystemOut     O - Preemptive
> Authentication set
> [10/12/10 0:52:56:698 GMT] 00000164 SystemOut     O - Redirecting to
> location:https://159.37.35.247/
> [10/12/10 0:52:56:778 GMT] 00000164 AuthChallenge I
> org.apache.commons.httpclient.auth.AuthChallengeProcessor selectAuthScheme
> Basic authentication scheme selected [10/12/10 0:52:56:786 GMT] 00000164
> HttpMethodDir I org.apache.commons.httpclient.HttpMethodDirector
> processWWWAuthChallenge Failure authenticating with BASIC
> 'FileDriveWWW'@159.37.35.247:443
> [10/12/10 0:52:56:792 GMT] 00000164 SystemOut     O - HTTPS
> RedirectResponseStatusCode=401
> [10/12/10 0:52:56:792 GMT] 00000164 SystemOut     O - HTTP/1.1 401
> Authorization Required
> [10/12/10 0:52:56:793 GMT] 00000164 HttpMethodBas W
> org.apache.commons.httpclient.HttpMethodBase getResponseBody Going to
> buffer response body of large or unknown size. Using
> getResponseBodyAsStream instead is recommended.
> [10/12/10 0:52:56:809 GMT] 00000164 SystemOut     O - <!DOCTYPE HTML
> PUBLIC "-//IETF//DTD HTML 2.0//EN">
> <HTML><HEAD>
> <TITLE>401 Authorization Required</TITLE> </HEAD><BODY> <H1>Authorization
> Required</H1> This server could not verify that you are authorized to
> access the document requested.  Either you supplied the wrong credentials
> (e.g., bad password), or your browser doesn't understand how to supply the
> credentials required.<P> </BODY></HTML>
> 
> [10/12/10 0:52:56:809 GMT] 00000164 SystemOut     O - File upload via
> HTTPS failed.
> 
> 
> Thanks
> Fayaz
> 
> 
> 
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: httpclient-users-unsubscribe@hc.apache.org
> For additional commands, e-mail: httpclient-users-help@hc.apache.org
> 
> 
> 

-- 
View this message in context: http://old.nabble.com/HTTPS-redirects-and-then-basic-auth-fails-tp29948240p31227255.html
Sent from the HttpClient-User mailing list archive at Nabble.com.


---------------------------------------------------------------------
To unsubscribe, e-mail: httpclient-users-unsubscribe@hc.apache.org
For additional commands, e-mail: httpclient-users-help@hc.apache.org


RE: HTTPS redirects and then basic auth fails

Posted by "Mudnal, Fayaz" <fm...@visa.com>.
This particular site redirected 3 times and then allowed for the file to be uploaded. I added some timeouts as well since files were getting uploaded partially. Hope this helps. Here is the code:

public void deliverByGenericHttps(String fileName, String proxyAddr,
                                      String proxyPort, String proxyUser,
                                      String proxyPass, String URL, String username, String password,
                                      InputStream inputStream)
            throws DeliveryException {
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Sending file: " + fileName + " to URL: " + URL);
        LOGGER.debug("username:" + username + " password:" + password);

        String header = "multipart/form-data";
        PostMethod method = null;
        Header ua = new Header("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0");
        try {
            HttpClient client = new HttpClient();
            client.getHttpConnectionManager().getParams().setConnectionTimeout(100000);
            client.getHttpConnectionManager().getParams().setSoTimeout(1200000);
            client.getHttpConnectionManager().getParams().setTcpNoDelay(true);
            client.getHttpConnectionManager().getParams().setLinger(240000);
            HostConfiguration hostConfig = client.getHostConfiguration();
            hostConfig.setHost(new URI(URL, true));

            if (proxyAddr != null && proxyAddr.length() > 0) {
                client.getHostConfiguration().setProxy(proxyAddr, Integer.parseInt(proxyPort));
                AuthScope proxyAuthScope = new AuthScope(proxyAddr, Integer.parseInt(proxyPort), AuthScope.ANY_REALM);
                client.getState().setProxyCredentials(proxyAuthScope,
                        new NTCredentials(proxyUser, proxyPass, "", ""));
            }

            LOGGER.debug("Open connection to: " + URL);
            if (username != null && password != null && username.trim().length() > 0 && password.trim().length() > 0) {
                LOGGER.debug("Setting credentials.");
                Credentials credentials = new UsernamePasswordCredentials(username, password);
                AuthScope authScope = new AuthScope(hostConfig.getHost(), hostConfig.getPort());
                HttpState state = client.getState();
                state.setCredentials(AuthScope.ANY, credentials);
                LOGGER.debug("Credentials set");
                List authPrefs = new ArrayList(3);
                authPrefs.add(AuthPolicy.BASIC);
                authPrefs.add(AuthPolicy.DIGEST);
                authPrefs.add(AuthPolicy.NTLM);

                client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);

                client.getParams().setAuthenticationPreemptive(true);
                LOGGER.debug("Preemptive Authentication set");
            }
            client.getParams().setParameter(CredentialsProvider.PROVIDER, new MyCredentialsProvider(username, password));
            client.getParams().setParameter("Connection", "Keep-Alive");

            method = new PostMethod(URL);
            method.setRequestHeader(ua);

            String inputFile = null;


            FilePart filePart = new FilePart("File", fileName, new File("Put file name here"));
            Part[] parts = new Part[1];
            parts[0] = filePart;
            HttpMethodParams methParams = method.getParams();
            methParams.setParameter("name", "File");
            methParams.setParameter("filename", fileName);
            methParams.setSoTimeout(1200000);
            MultipartRequestEntity multi = new MultipartRequestEntity(parts, methParams);
            method.setRequestEntity(multi);

            LOGGER.debug("File added to request body.");
            method.setRequestHeader("Connection", "Keep-Alive");
            method.setDoAuthentication(true);
            method.setFollowRedirects(false);
            HttpParams params = method.getParams();
            params.setParameter(CredentialsProvider.PROVIDER, new MyCredentialsProvider(username, password));
            params.setParameter("Connection", "Keep-Alive");
            LOGGER.debug("Uploading file...");
            int responseStatusCode = client.executeMethod(hostConfig, method);
            LOGGER.debug("HTTPS ResponseStatusCode=" + responseStatusCode);
            LOGGER.debug(method.getStatusLine());
            LOGGER.debug(method.getResponseBodyAsString());
            String cookie = method.getResponseHeader("Set-Cookie").getValue();
            LOGGER.debug("COOKIE=" + cookie);

            // Handle redirects
            int redirResponseStatusCode = 0;
            if (responseStatusCode == HttpStatus.SC_MOVED_TEMPORARILY ||
                    responseStatusCode == HttpStatus.SC_MOVED_PERMANENTLY ||
                    responseStatusCode == HttpStatus.SC_SEE_OTHER ||
                    responseStatusCode == HttpStatus.SC_TEMPORARY_REDIRECT) {

                LOGGER.debug("Redirection encountered:" + responseStatusCode);
                // The site redirects 3 times. So loop till auth is successful. Then upload the file after the loop.
                for (int i = 1; i < 11; i++) {
                    LOGGER.debug("Redirect attempt: " + i);
                    redirResponseStatusCode = 0;

                    Header locationHeader = method.getResponseHeader("location");
                    if (locationHeader == null) {
                        throw new DeliveryException("Redirected without a location");
                    }
                    String location = locationHeader.getValue();
                    hostConfig.setHost(new URI(location, true));
                    method.setURI(new URI(location, true));

                    if (username != null && password != null && username.trim().length() > 0 && password.trim().length() > 0) {
                        LOGGER.debug("Setting credentials for redirect.");
                        Credentials credentials = new UsernamePasswordCredentials(username, password);
                        AuthScope authScope = new AuthScope(hostConfig.getHost(), hostConfig.getPort());
                        HttpState state = client.getState();
                        state.setCredentials(AuthScope.ANY, credentials);
                        LOGGER.debug("Credentials set");
                        List authPrefs = new ArrayList(3);
                        authPrefs.add(AuthPolicy.BASIC);
                        authPrefs.add(AuthPolicy.DIGEST);
                        authPrefs.add(AuthPolicy.NTLM);

                        client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
                        client.getParams().setAuthenticationPreemptive(true);
                        LOGGER.debug("Preemptive Authentication set");
                    }

                    params = method.getParams();
                    params.setParameter(CredentialsProvider.PROVIDER, new MyCredentialsProvider(username, password));
                    LOGGER.debug("Redirecting to location:" + location);
                    redirResponseStatusCode = client.executeMethod(hostConfig, method);


                    LOGGER.debug("HTTPS RedirectResponseStatusCode=" + redirResponseStatusCode);
                    LOGGER.debug(method.getStatusLine());
                    LOGGER.debug(method.getResponseBodyAsString());


                    if (redirResponseStatusCode != HttpStatus.SC_MOVED_TEMPORARILY &&
                            redirResponseStatusCode != HttpStatus.SC_MOVED_PERMANENTLY &&
                            redirResponseStatusCode != HttpStatus.SC_SEE_OTHER &&
                            redirResponseStatusCode != HttpStatus.SC_TEMPORARY_REDIRECT)
                        break;

                    if (i == 10) {
                        LOGGER.debug("MAX Redirects exceeded.");
                    }
                }


                LOGGER.debug("NOW UPLOAD THE FILE to " + URL);
                // NOW UPLOAD THE FILE
                hostConfig.setHost(new URI(URL, true));
                method.setURI(new URI(URL, true));


                if (username != null && password != null && username.trim().length() > 0 && password.trim().length() > 0) {
                    LOGGER.debug("Setting credentials for redirect.");
                    Credentials credentials = new UsernamePasswordCredentials(username, password);
                    AuthScope authScope = new AuthScope(hostConfig.getHost(), hostConfig.getPort());
                    HttpState state = client.getState();
                    state.setCredentials(AuthScope.ANY, credentials);
                    LOGGER.debug("Credentials set");
                    List authPrefs = new ArrayList(3);
                    authPrefs.add(AuthPolicy.BASIC);
                    authPrefs.add(AuthPolicy.DIGEST);
                    authPrefs.add(AuthPolicy.NTLM);

                    client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
                    //client.getState().setAuthenticationPreemptive(true);
                    client.getParams().setAuthenticationPreemptive(true);
                    LOGGER.debug("Preemptive Authentication set");
                }

                params = method.getParams();
                params.setParameter(CredentialsProvider.PROVIDER, new MyCredentialsProvider(username, password));
                redirResponseStatusCode = client.executeMethod(hostConfig, method);

                LOGGER.debug("HTTPS RedirectResponseStatusCode=" + redirResponseStatusCode);
                LOGGER.debug(method.getStatusLine());
                LOGGER.debug(method.getResponseBodyAsString());

            }
            // Handle redirects

            if ((responseStatusCode >= 400) || (redirResponseStatusCode >= 400)) {
                LOGGER.debug("File upload via HTTPS failed.");
                throw new DeliveryException("File upload via HTTPS failed.");
            } else
                LOGGER.debug("File upload via HTTPS Successful.");

        } catch (Exception e) {
            LOGGER.debug("File upload via HTTPS failed.");
            e.printStackTrace();
            throw new DeliveryException(e);
        } finally {
            method.releaseConnection();
        }

    } // end of method

public static class MyCredentialsProvider implements CredentialsProvider {
        private String username, password;

        public MyCredentialsProvider(String username, String password) {
            this.username = username;
            this.password = password;
        }

        public Credentials getCredentials(AuthScheme authScheme, String s, int i, boolean b) throws CredentialsNotAvailableException {
            return new UsernamePasswordCredentials(username, password);  //To change body of implemented methods use File | Settings | File Templates.
        }
}

Fayaz

-----Original Message-----
From: Guri Bhai [mailto:guri.mailinglists@gmail.com]
Sent: Thursday, March 24, 2011 2:23 AM
To: httpclient-users@hc.apache.org
Subject: RE: HTTPS redirects and then basic auth fails



If you were able to solve this, can you help how? i am in a similar situation.



Mudnal, Fayaz K wrote:
>
> I set the auth realm to AuthScope.ANY, but this did not work either:
> httpstate.setCredentials(AuthScope.ANY, credentials);
>
> Fayaz
>
> -----Original Message-----
> From: Mudnal, Fayaz K [mailto:fmudnal@visa.com]
> Sent: Tuesday, October 12, 2010 4:19 PM
> To: httpclient-users@hc.apache.org
> Subject: HTTPS redirects and then basic auth fails
>
> Hi
> I am trying to upload a file to a https site. The site redirects 3
> times and then login fails with a 401 error. I am using HttpClient
> 3.0. The server folks said they could not see the credentials on their
> side. I would greatly appreciate any help. Here is the code:
>
>        String header = "multipart/form-data";
>         PostMethod method = null;
>
>         try {
>             HttpClient client = new HttpClient();
>             HostConfiguration hostConfig = client.getHostConfiguration();
>             hostConfig.setHost(new URI(URL, true));
>             LOGGER.debug("Open connection to: " + URL);
>             if (username != null && password != null &&
> username.trim().length() > 0 && password.trim().length() > 0) {
>                 LOGGER.debug("Setting credentials.");
>                 Credentials credentials = new
> UsernamePasswordCredentials(username, password);
>                 AuthScope authScope = new
> AuthScope(hostConfig.getHost(), hostConfig.getPort());
>                 HttpState state = client.getState();
>                 state.setCredentials(authScope, credentials);
>                 LOGGER.debug("Credentials set");
>                 List authPrefs = new ArrayList(3);
>                 authPrefs.add(AuthPolicy.BASIC);
>                 authPrefs.add(AuthPolicy.DIGEST);
>                 authPrefs.add(AuthPolicy.NTLM);
>
>
> client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY,
> authPrefs);
>                 client.getParams().setAuthenticationPreemptive(true);
>                 LOGGER.debug("Preemptive Authentication set");
>             }
>             RequestEntity entity = new
> InputStreamRequestEntity(inputStream, "application/upload");
>             method = new PostMethod(URL);
>             method.setRequestEntity(entity);
>             LOGGER.debug("FileInputStream set");
>             method.setRequestHeader("filename", fileName);
>             method.setRequestHeader("Content-Type", header);
>             method.setRequestHeader("Content-Disposition", "form-data");
>             method.setDoAuthentication(true);
>             method.setFollowRedirects( false );
>             LOGGER.debug("Uploading file...");
>             int responseStatusCode = client.executeMethod(hostConfig,
> method);
>             LOGGER.debug("HTTPS ResponseStatusCode=" +
> responseStatusCode);
>             LOGGER.debug(method.getStatusLine());
>             LOGGER.debug(method.getResponseBodyAsString());
>
>             // Handle redirects
>             int redirResponseStatusCode = 0;
>             if (responseStatusCode == HttpStatus.SC_MOVED_TEMPORARILY ||
>                     responseStatusCode ==
> HttpStatus.SC_MOVED_PERMANENTLY
> ||
>                     responseStatusCode == HttpStatus.SC_SEE_OTHER ||
>                     responseStatusCode ==
> HttpStatus.SC_TEMPORARY_REDIRECT) {
>
>                 LOGGER.debug("Redirection encountered:" +
> responseStatusCode);
>            // handle a max of 10 redirects
>                 for (int i = 1; i < 11; i++) {
>                     LOGGER.debug("Redirect attempt: " + i);
>                     redirResponseStatusCode = 0;
>
>                     Header locationHeader =
> method.getResponseHeader("location");
>                     if (locationHeader == null) {
>                       throw new DeliveryException("Redirected without
> a location");
>                     }
>                     String location = locationHeader.getValue();
>                     hostConfig.setHost(new URI(location, true));
>                     method.setURI(new URI(location, true));
>
>                     if (username != null && password != null &&
> username.trim().length() > 0 && password.trim().length() > 0) {
>                         LOGGER.debug("Setting credentials for redirect.");
>                         Credentials credentials = new
> UsernamePasswordCredentials(username, password);
>                         AuthScope authScope = new
> AuthScope(hostConfig.getHost(), hostConfig.getPort());
>                         HttpState state = client.getState();
>                         state.setCredentials(authScope, credentials);
>                         LOGGER.debug("Credentials set");
>                         List authPrefs = new ArrayList(3);
>                         authPrefs.add(AuthPolicy.BASIC);
>                         authPrefs.add(AuthPolicy.DIGEST);
>                         authPrefs.add(AuthPolicy.NTLM);
>
>
> client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY,
> authPrefs);
>
> //client.getState().setAuthenticationPreemptive(true);
>
> client.getParams().setAuthenticationPreemptive(true);
>                         LOGGER.debug("Preemptive Authentication set");
>                     }
>
>
>                     LOGGER.debug("Redirecting to location:" + location);
>                     redirResponseStatusCode =
> client.executeMethod(hostConfig, method);
>
>
>                     LOGGER.debug("HTTPS RedirectResponseStatusCode=" +
> redirResponseStatusCode);
>                     LOGGER.debug(method.getStatusLine());
>                     LOGGER.debug(method.getResponseBodyAsString());
>                     if (redirResponseStatusCode !=
> HttpStatus.SC_MOVED_TEMPORARILY &&
>                             redirResponseStatusCode !=
> HttpStatus.SC_MOVED_PERMANENTLY &&
>                             redirResponseStatusCode !=
> HttpStatus.SC_SEE_OTHER &&
>                             redirResponseStatusCode !=
> HttpStatus.SC_TEMPORARY_REDIRECT)
>                         break;
>
>                     if (i == 10) {LOGGER.debug("MAX Redirects
> exceeded.");}
>                 }
>             }
>             // Handle redirects
>
>             if ((responseStatusCode >= 400)||(redirResponseStatusCode
> >=
> 400)) {
>                 LOGGER.debug("File upload via HTTPS failed.");
>                 throw new DeliveryException("File upload via HTTPS
> failed.");
>             } else
>                 LOGGER.debug("File upload via HTTPS Successful.");
>
>         } catch (Exception e) {
>             LOGGER.debug("File upload via HTTPS failed.");
>             e.printStackTrace();
>             throw new DeliveryException(e);
>         } finally {
>             method.releaseConnection();
>         }
>
> Here are the logs:
> [10/12/10 0:52:56:136 GMT] 00000164 SystemOut     O - username:xxxxx
> password:xxxxx
> [10/12/10 0:52:56:137 GMT] 00000164 SystemOut     O - Open connection to:
> https://159.37.35.247/
> [10/12/10 0:52:56:137 GMT] 00000164 SystemOut     O - Setting credentials.
> [10/12/10 0:52:56:138 GMT] 00000164 SystemOut     O - Credentials set
> [10/12/10 0:52:56:139 GMT] 00000164 SystemOut     O - Preemptive
> Authentication set
> [10/12/10 0:52:56:140 GMT] 00000164 SystemOut     O - FileInputStream set
> [10/12/10 0:52:56:141 GMT] 00000164 SystemOut     O - Uploading file...
> [10/12/10 0:52:56:452 GMT] 00000164 HttpMethodDir I
> org.apache.commons.httpclient.HttpMethodDirector isRedirectNeeded
> Redirect requested but followRedirects is disabled
> [10/12/10 0:52:56:459 GMT] 00000164 SystemOut     O - HTTPS
> ResponseStatusCode=302
> [10/12/10 0:52:56:459 GMT] 00000164 SystemOut     O - HTTP/1.1 302 Found
> [10/12/10 0:52:56:459 GMT] 00000164 HttpMethodBas W
> org.apache.commons.httpclient.HttpMethodBase getResponseBody Going to
> buffer response body of large or unknown size. Using
> getResponseBodyAsStream instead is recommended.
> [10/12/10 0:52:56:475 GMT] 00000164 SystemOut     O - <!DOCTYPE HTML
> PUBLIC "-//IETF//DTD HTML 2.0//EN">
> <HTML><HEAD>
> <TITLE>302 Found</TITLE>
> </HEAD><BODY>
> <H1>Found</H1>
> The document has moved
> https://159.37.35.247:443/?&amp;STCO=1TLOxTpeXQHAAAEqsStY&amp;STCOEND
> here .<P> <P>Additionally, a 302 Found error was encountered while
> trying to use an ErrorDocument to handle the request.
> </BODY></HTML>
>
> [10/12/10 0:52:56:475 GMT] 00000164 SystemOut     O - Redirection
> encountered:302
> [10/12/10 0:52:56:476 GMT] 00000164 SystemOut     O - Redirect attempt: 1
> [10/12/10 0:52:56:476 GMT] 00000164 SystemOut     O - Setting credentials
> for redirect.
> [10/12/10 0:52:56:477 GMT] 00000164 SystemOut     O - Credentials set
> [10/12/10 0:52:56:478 GMT] 00000164 SystemOut     O - Preemptive
> Authentication set
> [10/12/10 0:52:56:478 GMT] 00000164 SystemOut     O - Redirecting to
> location:https://159.37.35.247:443/?&STCO=1TLOxTpeXQHAAAEqsStY&STCOEND
> [10/12/10 0:52:56:561 GMT] 00000164 HttpMethodDir I
> org.apache.commons.httpclient.HttpMethodDirector isRedirectNeeded
> Redirect requested but followRedirects is disabled
> [10/12/10 0:52:56:568 GMT] 00000164 SystemOut     O - HTTPS
> RedirectResponseStatusCode=302
> [10/12/10 0:52:56:568 GMT] 00000164 SystemOut     O - HTTP/1.1 302 Found
> [10/12/10 0:52:56:569 GMT] 00000164 HttpMethodBas W
> org.apache.commons.httpclient.HttpMethodBase getResponseBody Going to
> buffer response body of large or unknown size. Using
> getResponseBodyAsStream instead is recommended.
> [10/12/10 0:52:56:584 GMT] 00000164 SystemOut     O - <!DOCTYPE HTML
> PUBLIC "-//IETF//DTD HTML 2.0//EN">
> <HTML><HEAD>
> <TITLE>302 Found</TITLE>
> </HEAD><BODY>
> <H1>Found</H1>
> The document has moved
> https://159.37.35.247/?&amp;STCO=2TLOxTpeXQHAAAEqsStY&amp;STCOEND here
> .<P> <P>Additionally, a 302 Found error was encountered while trying
> to use an ErrorDocument to handle the request.
> </BODY></HTML>
>
> [10/12/10 0:52:56:585 GMT] 00000164 SystemOut     O - Redirect attempt: 2
> [10/12/10 0:52:56:585 GMT] 00000164 SystemOut     O - Setting credentials
> for redirect.
> [10/12/10 0:52:56:586 GMT] 00000164 SystemOut     O - Credentials set
> [10/12/10 0:52:56:586 GMT] 00000164 SystemOut     O - Preemptive
> Authentication set
> [10/12/10 0:52:56:587 GMT] 00000164 SystemOut     O - Redirecting to
> location:https://159.37.35.247/?&STCO=2TLOxTpeXQHAAAEqsStY&STCOEND
> [10/12/10 0:52:56:672 GMT] 00000164 HttpMethodDir I
> org.apache.commons.httpclient.HttpMethodDirector isRedirectNeeded
> Redirect requested but followRedirects is disabled
> [10/12/10 0:52:56:680 GMT] 00000164 SystemOut     O - HTTPS
> RedirectResponseStatusCode=302
> [10/12/10 0:52:56:681 GMT] 00000164 SystemOut     O - HTTP/1.1 302 Found
> [10/12/10 0:52:56:681 GMT] 00000164 HttpMethodBas W
> org.apache.commons.httpclient.HttpMethodBase getResponseBody Going to
> buffer response body of large or unknown size. Using
> getResponseBodyAsStream instead is recommended.
> [10/12/10 0:52:56:696 GMT] 00000164 SystemOut     O - <!DOCTYPE HTML
> PUBLIC "-//IETF//DTD HTML 2.0//EN">
> <HTML><HEAD>
> <TITLE>302 Found</TITLE>
> </HEAD><BODY>
> <H1>Found</H1>
> The document has moved  https://159.37.35.247/ here .<P>
> <P>Additionally, a 302 Found error was encountered while trying to use
> an ErrorDocument to handle the request.
> </BODY></HTML>
>
> [10/12/10 0:52:56:696 GMT] 00000164 SystemOut     O - Redirect attempt: 3
> [10/12/10 0:52:56:697 GMT] 00000164 SystemOut     O - Setting credentials
> for redirect.
> [10/12/10 0:52:56:698 GMT] 00000164 SystemOut     O - Credentials set
> [10/12/10 0:52:56:698 GMT] 00000164 SystemOut     O - Preemptive
> Authentication set
> [10/12/10 0:52:56:698 GMT] 00000164 SystemOut     O - Redirecting to
> location:https://159.37.35.247/
> [10/12/10 0:52:56:778 GMT] 00000164 AuthChallenge I
> org.apache.commons.httpclient.auth.AuthChallengeProcessor
> selectAuthScheme Basic authentication scheme selected [10/12/10
> 0:52:56:786 GMT] 00000164 HttpMethodDir I
> org.apache.commons.httpclient.HttpMethodDirector
> processWWWAuthChallenge Failure authenticating with BASIC
> 'FileDriveWWW'@159.37.35.247:443
> [10/12/10 0:52:56:792 GMT] 00000164 SystemOut     O - HTTPS
> RedirectResponseStatusCode=401
> [10/12/10 0:52:56:792 GMT] 00000164 SystemOut     O - HTTP/1.1 401
> Authorization Required
> [10/12/10 0:52:56:793 GMT] 00000164 HttpMethodBas W
> org.apache.commons.httpclient.HttpMethodBase getResponseBody Going to
> buffer response body of large or unknown size. Using
> getResponseBodyAsStream instead is recommended.
> [10/12/10 0:52:56:809 GMT] 00000164 SystemOut     O - <!DOCTYPE HTML
> PUBLIC "-//IETF//DTD HTML 2.0//EN">
> <HTML><HEAD>
> <TITLE>401 Authorization Required</TITLE> </HEAD><BODY>
> <H1>Authorization Required</H1> This server could not verify that you
> are authorized to access the document requested.  Either you supplied
> the wrong credentials (e.g., bad password), or your browser doesn't
> understand how to supply the credentials required.<P> </BODY></HTML>
>
> [10/12/10 0:52:56:809 GMT] 00000164 SystemOut     O - File upload via
> HTTPS failed.
>
>
> Thanks
> Fayaz
>
>
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: httpclient-users-unsubscribe@hc.apache.org
> For additional commands, e-mail: httpclient-users-help@hc.apache.org
>
>
>

--
View this message in context: http://old.nabble.com/HTTPS-redirects-and-then-basic-auth-fails-tp29948240p31227255.html
Sent from the HttpClient-User mailing list archive at Nabble.com.


---------------------------------------------------------------------
To unsubscribe, e-mail: httpclient-users-unsubscribe@hc.apache.org
For additional commands, e-mail: httpclient-users-help@hc.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: httpclient-users-unsubscribe@hc.apache.org
For additional commands, e-mail: httpclient-users-help@hc.apache.org