Apache HttpClient Socks5 proxy with authentication










0















I'm trying to use a Socks5 proxy server for requests to a certain target (host) that requires proxy in my Java application. I'm using Apache Http library (v. 4.5.4). I have lots of different other targets which do not require proxy, so setting up proxy globally for the whole application is not an option for me. So i set up proxy for a certain instance of HttpClient. The proxy requires authentication with login and pass.



My solution is based on this question additionally adding authentication parameters as described in documentation.



Here is my code:



private void sendSocks5Request(StringEntity requestEntity) throws Exception 

Registry<ConnectionSocketFactory> reg = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new MyConnectionSocketFactory(SSLContexts.createSystemDefault()))
.build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(reg);

Credentials credentials = new UsernamePasswordCredentials("proxy_user","proxy_pass");
AuthScope authScope = new AuthScope("my.proxy.com", 1080);
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(authScope, credentials);

CloseableHttpClient httpclient = HttpClients.custom()
.setConnectionManager(cm)
.setDefaultCredentialsProvider(credsProvider)
.build();

try
InetSocketAddress socksaddr = new InetSocketAddress("my.proxy.com", 1080);
HttpClientContext context = HttpClientContext.create();
context.setAttribute("socks.address", socksaddr);

HttpHost target = new HttpHost("api.telegram.org", 80, "https");
HttpPost request = new HttpPost("/bot<bot_token_here>");
request.setEntity(requestEntity);

System.out.println("Executing request " + request + " to " + target + " via SOCKS proxy " + socksaddr);
CloseableHttpResponse response = httpclient.execute(target, request, context);
try
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
EntityUtils.consume(response.getEntity());
catch (Exception ex)
ex.getMessage();
finally
response.close();

catch (Exception ex)
ex.getMessage();
finally
httpclient.close();




Proxy seems to work, but i get a Authentication failed error. Logs on the proxy server itself show that provided authentication contains not the proxy_user user, but my machine's system user. So it seems like HttpClient ignores provided credentials and takes it from the system.



What am i doing wrong?










share|improve this question






















  • We have the same issue, the proxy we are using does not require authentication but since our java code is essentially sending the system user (which is actually a security concern since it offers information the target system does not need!!!) the proxy throws an error which causes the whole communication to fail. Did you make any way? It seems this question is the only one that tackles this issue!

    – DJGummikuh
    Nov 9 '18 at 8:54















0















I'm trying to use a Socks5 proxy server for requests to a certain target (host) that requires proxy in my Java application. I'm using Apache Http library (v. 4.5.4). I have lots of different other targets which do not require proxy, so setting up proxy globally for the whole application is not an option for me. So i set up proxy for a certain instance of HttpClient. The proxy requires authentication with login and pass.



My solution is based on this question additionally adding authentication parameters as described in documentation.



Here is my code:



private void sendSocks5Request(StringEntity requestEntity) throws Exception 

Registry<ConnectionSocketFactory> reg = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new MyConnectionSocketFactory(SSLContexts.createSystemDefault()))
.build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(reg);

Credentials credentials = new UsernamePasswordCredentials("proxy_user","proxy_pass");
AuthScope authScope = new AuthScope("my.proxy.com", 1080);
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(authScope, credentials);

CloseableHttpClient httpclient = HttpClients.custom()
.setConnectionManager(cm)
.setDefaultCredentialsProvider(credsProvider)
.build();

try
InetSocketAddress socksaddr = new InetSocketAddress("my.proxy.com", 1080);
HttpClientContext context = HttpClientContext.create();
context.setAttribute("socks.address", socksaddr);

HttpHost target = new HttpHost("api.telegram.org", 80, "https");
HttpPost request = new HttpPost("/bot<bot_token_here>");
request.setEntity(requestEntity);

System.out.println("Executing request " + request + " to " + target + " via SOCKS proxy " + socksaddr);
CloseableHttpResponse response = httpclient.execute(target, request, context);
try
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
EntityUtils.consume(response.getEntity());
catch (Exception ex)
ex.getMessage();
finally
response.close();

catch (Exception ex)
ex.getMessage();
finally
httpclient.close();




Proxy seems to work, but i get a Authentication failed error. Logs on the proxy server itself show that provided authentication contains not the proxy_user user, but my machine's system user. So it seems like HttpClient ignores provided credentials and takes it from the system.



What am i doing wrong?










share|improve this question






















  • We have the same issue, the proxy we are using does not require authentication but since our java code is essentially sending the system user (which is actually a security concern since it offers information the target system does not need!!!) the proxy throws an error which causes the whole communication to fail. Did you make any way? It seems this question is the only one that tackles this issue!

    – DJGummikuh
    Nov 9 '18 at 8:54













0












0








0


1






I'm trying to use a Socks5 proxy server for requests to a certain target (host) that requires proxy in my Java application. I'm using Apache Http library (v. 4.5.4). I have lots of different other targets which do not require proxy, so setting up proxy globally for the whole application is not an option for me. So i set up proxy for a certain instance of HttpClient. The proxy requires authentication with login and pass.



My solution is based on this question additionally adding authentication parameters as described in documentation.



Here is my code:



private void sendSocks5Request(StringEntity requestEntity) throws Exception 

Registry<ConnectionSocketFactory> reg = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new MyConnectionSocketFactory(SSLContexts.createSystemDefault()))
.build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(reg);

Credentials credentials = new UsernamePasswordCredentials("proxy_user","proxy_pass");
AuthScope authScope = new AuthScope("my.proxy.com", 1080);
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(authScope, credentials);

CloseableHttpClient httpclient = HttpClients.custom()
.setConnectionManager(cm)
.setDefaultCredentialsProvider(credsProvider)
.build();

try
InetSocketAddress socksaddr = new InetSocketAddress("my.proxy.com", 1080);
HttpClientContext context = HttpClientContext.create();
context.setAttribute("socks.address", socksaddr);

HttpHost target = new HttpHost("api.telegram.org", 80, "https");
HttpPost request = new HttpPost("/bot<bot_token_here>");
request.setEntity(requestEntity);

System.out.println("Executing request " + request + " to " + target + " via SOCKS proxy " + socksaddr);
CloseableHttpResponse response = httpclient.execute(target, request, context);
try
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
EntityUtils.consume(response.getEntity());
catch (Exception ex)
ex.getMessage();
finally
response.close();

catch (Exception ex)
ex.getMessage();
finally
httpclient.close();




Proxy seems to work, but i get a Authentication failed error. Logs on the proxy server itself show that provided authentication contains not the proxy_user user, but my machine's system user. So it seems like HttpClient ignores provided credentials and takes it from the system.



What am i doing wrong?










share|improve this question














I'm trying to use a Socks5 proxy server for requests to a certain target (host) that requires proxy in my Java application. I'm using Apache Http library (v. 4.5.4). I have lots of different other targets which do not require proxy, so setting up proxy globally for the whole application is not an option for me. So i set up proxy for a certain instance of HttpClient. The proxy requires authentication with login and pass.



My solution is based on this question additionally adding authentication parameters as described in documentation.



Here is my code:



private void sendSocks5Request(StringEntity requestEntity) throws Exception 

Registry<ConnectionSocketFactory> reg = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new MyConnectionSocketFactory(SSLContexts.createSystemDefault()))
.build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(reg);

Credentials credentials = new UsernamePasswordCredentials("proxy_user","proxy_pass");
AuthScope authScope = new AuthScope("my.proxy.com", 1080);
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(authScope, credentials);

CloseableHttpClient httpclient = HttpClients.custom()
.setConnectionManager(cm)
.setDefaultCredentialsProvider(credsProvider)
.build();

try
InetSocketAddress socksaddr = new InetSocketAddress("my.proxy.com", 1080);
HttpClientContext context = HttpClientContext.create();
context.setAttribute("socks.address", socksaddr);

HttpHost target = new HttpHost("api.telegram.org", 80, "https");
HttpPost request = new HttpPost("/bot<bot_token_here>");
request.setEntity(requestEntity);

System.out.println("Executing request " + request + " to " + target + " via SOCKS proxy " + socksaddr);
CloseableHttpResponse response = httpclient.execute(target, request, context);
try
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
EntityUtils.consume(response.getEntity());
catch (Exception ex)
ex.getMessage();
finally
response.close();

catch (Exception ex)
ex.getMessage();
finally
httpclient.close();




Proxy seems to work, but i get a Authentication failed error. Logs on the proxy server itself show that provided authentication contains not the proxy_user user, but my machine's system user. So it seems like HttpClient ignores provided credentials and takes it from the system.



What am i doing wrong?







java authentication proxy apache-httpclient-4.x socks






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jul 10 '18 at 15:30









EmptyfruitEmptyfruit

11819




11819












  • We have the same issue, the proxy we are using does not require authentication but since our java code is essentially sending the system user (which is actually a security concern since it offers information the target system does not need!!!) the proxy throws an error which causes the whole communication to fail. Did you make any way? It seems this question is the only one that tackles this issue!

    – DJGummikuh
    Nov 9 '18 at 8:54

















  • We have the same issue, the proxy we are using does not require authentication but since our java code is essentially sending the system user (which is actually a security concern since it offers information the target system does not need!!!) the proxy throws an error which causes the whole communication to fail. Did you make any way? It seems this question is the only one that tackles this issue!

    – DJGummikuh
    Nov 9 '18 at 8:54
















We have the same issue, the proxy we are using does not require authentication but since our java code is essentially sending the system user (which is actually a security concern since it offers information the target system does not need!!!) the proxy throws an error which causes the whole communication to fail. Did you make any way? It seems this question is the only one that tackles this issue!

– DJGummikuh
Nov 9 '18 at 8:54





We have the same issue, the proxy we are using does not require authentication but since our java code is essentially sending the system user (which is actually a security concern since it offers information the target system does not need!!!) the proxy throws an error which causes the whole communication to fail. Did you make any way? It seems this question is the only one that tackles this issue!

– DJGummikuh
Nov 9 '18 at 8:54












1 Answer
1






active

oldest

votes


















0














I've spent a few days struggling with the same problem.
For me, the simplest way is to use java's Authenticator
Just add this code before execute:



Authenticator.setDefault(new Authenticator() 
protected PasswordAuthentication getPasswordAuthentication()
return new PasswordAuthentication(proxyUser, proxyPassword.toCharArray());

);


After that, a socket should send your credentials. You may debug the java.net.SocksSocketImpl#authenticate(byte, java.io.InputStream, java.io.BufferedOutputStream, long) method if you have an interest.



I've tried to use many other methods, but they all don't work for me. I assume that setDefaultCredentialsProvider is responding for authentication on the target, not on the proxy. I didn't debug so deep yet. I still trying to figure out how to solve this problem more elegant. Let me know if you will find a better solution.






share|improve this answer






















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f51269160%2fapache-httpclient-socks5-proxy-with-authentication%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    I've spent a few days struggling with the same problem.
    For me, the simplest way is to use java's Authenticator
    Just add this code before execute:



    Authenticator.setDefault(new Authenticator() 
    protected PasswordAuthentication getPasswordAuthentication()
    return new PasswordAuthentication(proxyUser, proxyPassword.toCharArray());

    );


    After that, a socket should send your credentials. You may debug the java.net.SocksSocketImpl#authenticate(byte, java.io.InputStream, java.io.BufferedOutputStream, long) method if you have an interest.



    I've tried to use many other methods, but they all don't work for me. I assume that setDefaultCredentialsProvider is responding for authentication on the target, not on the proxy. I didn't debug so deep yet. I still trying to figure out how to solve this problem more elegant. Let me know if you will find a better solution.






    share|improve this answer



























      0














      I've spent a few days struggling with the same problem.
      For me, the simplest way is to use java's Authenticator
      Just add this code before execute:



      Authenticator.setDefault(new Authenticator() 
      protected PasswordAuthentication getPasswordAuthentication()
      return new PasswordAuthentication(proxyUser, proxyPassword.toCharArray());

      );


      After that, a socket should send your credentials. You may debug the java.net.SocksSocketImpl#authenticate(byte, java.io.InputStream, java.io.BufferedOutputStream, long) method if you have an interest.



      I've tried to use many other methods, but they all don't work for me. I assume that setDefaultCredentialsProvider is responding for authentication on the target, not on the proxy. I didn't debug so deep yet. I still trying to figure out how to solve this problem more elegant. Let me know if you will find a better solution.






      share|improve this answer

























        0












        0








        0







        I've spent a few days struggling with the same problem.
        For me, the simplest way is to use java's Authenticator
        Just add this code before execute:



        Authenticator.setDefault(new Authenticator() 
        protected PasswordAuthentication getPasswordAuthentication()
        return new PasswordAuthentication(proxyUser, proxyPassword.toCharArray());

        );


        After that, a socket should send your credentials. You may debug the java.net.SocksSocketImpl#authenticate(byte, java.io.InputStream, java.io.BufferedOutputStream, long) method if you have an interest.



        I've tried to use many other methods, but they all don't work for me. I assume that setDefaultCredentialsProvider is responding for authentication on the target, not on the proxy. I didn't debug so deep yet. I still trying to figure out how to solve this problem more elegant. Let me know if you will find a better solution.






        share|improve this answer













        I've spent a few days struggling with the same problem.
        For me, the simplest way is to use java's Authenticator
        Just add this code before execute:



        Authenticator.setDefault(new Authenticator() 
        protected PasswordAuthentication getPasswordAuthentication()
        return new PasswordAuthentication(proxyUser, proxyPassword.toCharArray());

        );


        After that, a socket should send your credentials. You may debug the java.net.SocksSocketImpl#authenticate(byte, java.io.InputStream, java.io.BufferedOutputStream, long) method if you have an interest.



        I've tried to use many other methods, but they all don't work for me. I assume that setDefaultCredentialsProvider is responding for authentication on the target, not on the proxy. I didn't debug so deep yet. I still trying to figure out how to solve this problem more elegant. Let me know if you will find a better solution.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 14 '18 at 22:14









        Ignatiy VoronovIgnatiy Voronov

        315




        315





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f51269160%2fapache-httpclient-socks5-proxy-with-authentication%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            這個網誌中的熱門文章

            How to read a connectionString WITH PROVIDER in .NET Core?

            Museum of Modern and Contemporary Art of Trento and Rovereto

            In R, how to develop a multiplot heatmap.2 figure showing key labels successfully