所以我在使用 NTLM 身份验证的公司代理下工作。身份验证已正确检测,我可以通过代理访问需要访问的不同 API。
当我尝试访问需要基本身份验证(GET 请求)的 API 端点时,出现了问题。每当我尝试通过我的代码访问它时,我都会收到未经授权的 401,并且我可以在 header 中看到我得到“WWW-Authenticate:Basic Realm =“Realm”。
我尝试过各种不同的方法,但最终的结果总是一样。
我尝试直接在 URI 中设置用户名和密码:
HttpGet request = new HttpGet(https://username:password@APIHost.com/end/point)
我尝试使用基本凭据提供程序:
CredentialsProvider provider = new BasicCredentialsProvider();
provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
我尝试在请求中手动添加 Base64 授权 header :
request.addHeader("Authorization", "Basic .........................");
另外,请注意,我可以使用 PostMan 甚至网络浏览器通过代理访问此端点。
编辑
我注意到,实际上,如果我连续运行 HttpRequest 两次(使用相同的 SessionID 等),第一个请求将失败并返回 401,但第二个请求实际上会成功。知道为什么会发生这种情况吗?我想也许代理没有转发基本身份验证...
我尝试了更多的事情,但目前一切都是徒劳的。
任何帮助将不胜感激! :)
最佳答案
也许您可以尝试另外设置代理,如以下链接中的示例所示:-
https://www.tutorialspoint.com/apache_httpclient/apache_httpclient_proxy_authentication.htm
public class ProxyAuthenticationExample {
public static void main(String[] args) throws Exception {
//Creating the CredentialsProvider object
CredentialsProvider credsProvider = new BasicCredentialsProvider();
//Setting the credentials
credsProvider.setCredentials(new AuthScope("example.com", 80),
new UsernamePasswordCredentials("user", "mypass"));
credsProvider.setCredentials(new AuthScope("localhost", 8000),
new UsernamePasswordCredentials("abc", "passwd"));
//Creating the HttpClientBuilder
HttpClientBuilder clientbuilder = HttpClients.custom();
//Setting the credentials
clientbuilder = clientbuilder.setDefaultCredentialsProvider(credsProvider);
//Building the CloseableHttpClient object
CloseableHttpClient httpclient = clientbuilder.build();
//Create the target and proxy hosts
HttpHost targetHost = new HttpHost("example.com", 80, "http");
HttpHost proxyHost = new HttpHost("localhost", 8000, "http");
//Setting the proxy
RequestConfig.Builder reqconfigconbuilder= RequestConfig.custom();
reqconfigconbuilder = reqconfigconbuilder.setProxy(proxyHost);
RequestConfig config = reqconfigconbuilder.build();
//Create the HttpGet request object
HttpGet httpget = new HttpGet("/");
//Setting the config to the request
httpget.setConfig(config);
//Printing the status line
HttpResponse response = httpclient.execute(targetHost, httpget);
System.out.println(response.getStatusLine());
} }
关于java - 在公司代理 HTTP 客户端 java 下进行基本身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58910254/