Trying to connect to a resource which is protected with NTLM authentication.
When making a request I get a response 401 unauthenticated, but httpclient doesn't perform NTLM authentication after that.
Added Interceptor to see the communication and it doesn't even attempt to authenticate:
Request:
POST/NAV/xxxxxxxxx
Content-type: text/xml; charset=utf-8
SOAPAction:
Content-Length: 359
Host: xxx.local:7051
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.5.4 (Java/1.8.0_181)
Accept-Encoding: gzip,deflate
Response:
Unauthorized
Content-Length: 0
Server: Microsoft-HTTPAPI/2.0
WWW-Authenticate: Negotiate
Date: Wed, 26 Sep 2018 10:37:56 GMT
No requests made after that.
Any suggestions what can be wrong here?
Here is my code:
NTCredentials credentials = new NTCredentials("testuser", "pass1", null, "stt.local");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, credentials);
ArrayList<String> authPrefs = new ArrayList<String>();
authPrefs.add(AuthSchemes.NTLM);
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(30000)
.setConnectTimeout(30000)
.setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM))
.setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC))
.build();
HttpClient client = HttpClientBuilder.
create().
setDefaultCredentialsProvider(credsProvider).
setDefaultRequestConfig(requestConfig).
addInterceptorLast(new LoggingRequestInterceptor()).
addInterceptorLast(new LoggingResponseInterceptor()).
build();
HttpPost post = new HttpPost(endpoint); //Provide Request URL
try {
StringEntity input = new StringEntity(bodyAsString);
input.setContentType("text/xml; charset=utf-8");
post.setEntity(input);
post.setHeader("Content-type", "text/xml; charset=utf-8");
post.setHeader("SOAPAction", ""); //Provide Soap action
org.apache.http.HttpResponse response = client.execute(post);
}
The parameters to that NTCredentials constructor should have separate username and domain name.
Parameters:
userName - The user name. This should not include the domain to authenticate with. For example: "user" is correct whereas "DOMAIN\user" is not.
password - The password.
workstation - The workstation the authentication request is originating from.
Essentially, the computer name for this machine.
domain - The domain to authenticate within.
Related
Postman has a setting which corrects the method on calls which redirect.
Postman Settings : Follow original HTTP Method
Follow original HTTP Method: Redirect with the original HTTP method
instead of the default behavior of redirecting with GET.
How can we implement this in Java code? I am using OKHttp. I am also open to using other libs if necessary.
Error:{"detail": "Method "GET" not allowed."}
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("text/plain");
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("job_id","z5G7h3l6a1kMvyS65NP3c0a2-MRSuDJL0EWa7zDjsGs=")
.addFormDataPart("firstname","Jhon")
.addFormDataPart("lastname","Doe")
.addFormDataPart("email","john.doe#gmail.com")
.addFormDataPart("city","Dallas")
.addFormDataPart("state","TX")
.addFormDataPart("country","US")
.addFormDataPart("mobile_number","555-5555")
.addFormDataPart("file_name","jd.pdf")
.addFormDataPart("resume","/C:/Users/test/Downloads/test.pdf",
RequestBody.create(MediaType.parse("application/octet-stream"),
new File("/C:/Users/test/Downloads/test.pdf")))
.build();
Request request = new Request.Builder()
.url("https://api.ceipal.com/xx-yy-zzz/ApplyJobWithOutRegistration")
.method("POST", body)
.build();
Response response = client.newCall(request).execute();
This results in these calls in the interceptor:
url: https://api.ceipal.com/xxx-yyy-zzz/ApplyJobWithOutRegistration
method:POST
header:Content-Type: multipart/form-data; boundary=21938c2b-0d98-4851-8532-a91ba219491d
Content-Length: 157614
Host: api.ceipal.com
Connection: Keep-Alive
Accept-Encoding: gzip
User-Agent: okhttp/4.9.1
url: https://api.ceipal.com/xxx-yyy-zzz/ApplyJobWithOutRegistration/
method:GET
header:Host: api.ceipal.com
Connection: Keep-Alive
Accept-Encoding: gzip
User-Agent: okhttp/4.9.1
as the redirect replaces the POST with GET the call responds with this error:
Error:{"detail": "Method "GET" not allowed."}
When I try this call in Postman,
Without the setting I get a response: Error:{"detail": "Method "GET" not allowed."}
With the setting turned on - {"status": 201, "success": 0, "message": "You have already applied for this job."}
I need to check this scenario: When I access a URL, it should be redirected to a new URL, curl is good:
curl -i http://localhost:8080/index.html
HTTP/1.1 302 Found
Date: Fri, 04 Oct 2019 18:57:07 GMT
Location: http://localhost:8080/
Content-Length: 0
I get the 302 status code as expected. But when I try to run this using apache http client in Java, I get the status code 200 instead. Java code:
HttpGet request = new HttpGet("http://localhost:8080/index.html");
HttpClient client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(request);
System.out.println("Completed executing the request, status: " + response.getStatusLine());
Assert.assertEquals(response.getStatusLine().getStatusCode(), 200);
How can I also get the 302 status code in JAVA ?
You need to disable redirects. Try this:
HttpParams params = new BasicHttpParams();
params.setParameter("http.protocol.handle-redirects",false);
HttpGet request = new HttpGet("http://localhost:8080/index.html");
request.setParams(params);
I need to add the authentication while sending xml-rpc request.
POST /Air HTTP/1.1
Content-Length: 1704
Content-Type: text/xml
User-Agent: UGw Server/5.0/1.0
Host: localhost
Authorization: Basic ZmRzdXNlcjpmZHN1c2Vy
But not able to find how to do it.
This is how I am sending the request in JAVA
XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
config.setServerURL(new URL("http://localhost:8088/RPC2"));
config.setUserAgent("UGw Server/5.0/1.0");
XmlRpcClient client = new XmlRpcClient();
client.setConfig(config);
Integer result = (Integer)client.execute("translate.sum", params);
INTRO
In order to automate some reports I registered a project on Google Developer Console, enabled Webmaster Tools API, Site Verification API.
(For scopes:
String [] SCOPESArray= {"https://www.googleapis.com/auth/webmasters",
"https://sites.google.com/feeds/"};
)
Then I've built service account credential in my Java application:
GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(SCOPES)
.setServiceAccountPrivateKeyFromP12File(p12)
.build();
and service:
Webmasters service = new Webmasters.Builder(httpTransport, jsonFactory, credential).setApplicationName("APP NAME").build();
Then I've successfully got all sites that are verified:
Webmasters.Sites.List request = service.sites().list();
SitesListResponse siteList = request.execute();
for (WmxSite currentSite : siteList.getSiteEntry()) {
System.out.println(currentSite+": "+ currentSite.getPermissionLevel());
}
Output:
{"permissionLevel":"siteFullUser","siteUrl":"http://www.mysite1.com/"}: siteFullUser
{"permissionLevel":"siteOwner","siteUrl":"http://www.mysite2.net/"}: siteOwner
THE PROBLEM:
How to download latest links *.csv file from page Search Traffic\Links to my site? (Page https://www.google.com/webmasters/tools/external-links-domain?hl=en&siteUrl=http://www.mysite2.net/ contains link to this file).
My idea was to use request as first step:
String access_token = credential.getAccessToken();
HttpRequestFactory requestFactory = service.getRequestFactory();
GenericUrl url = new GenericUrl("https://www.google.com/webmasters/tools/external-links-domain?hl=en&siteUrl=http://www.mysite2.net/?access_token="+access_token);
HttpRequest httpRequest = requestFactory.buildGetRequest(url);
HttpResponse response = httpRequest.execute();
But I get an error:
HTTP/1.1 401 Unauthorized
Alternate-protocol: 443:quic,p=1
Content-length: 147
X-xss-protection: 1; mode=block
X-content-type-options: nosniff
Transfer-encoding: chunked
Expires: Sat, 13 Jun 2015 17:00:20 GMT
Server: GSE
-content-encoding: gzip
Cache-control: private, max-age=0
Date: Sat, 13 Jun 2015 17:00:20 GMT
X-frame-options: SAMEORIGIN
Content-type: text/html; charset=UTF-8
Www-authenticate: Bearer realm="https://www.google.com/accounts/"
Note: Previous combination OAuth + Webmaster (V2) worked fine for me: the response to analogous request contained link to desired *.csv file
I am doing an HttpPost to send data to LoopBack and get the response. I am getting an error as below from LoopBack :
HTTP/1.1 422 Unprocessable Entity [X-Powered-By: Express, Vary: Origin, Accept-Encoding, Access-Control-Allow-Credentials: true, Content-Type: application/json; charset=utf-8, Content-Length: 1528, Date: Thu, 18 Dec 2014 18:13:45 GMT, Connection: keep-alive]
So, what I did in java is created a json from a java object , when I used this JSON in loopback api explorer, the data was inserted and gave me response 200, but doing from Java, I am getting this error. Does anyone have an idea about this.
Java code is as below
JSONObject json = new JSONObject(jsonString);
StringEntity stringEntity = new StringEntity(json.toString());
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(POST_CLAIM_URL);
post.setEntity(stringEntity);
HttpResponse httpResponse = null;
httpResponse = client.execute(post);
I had make sure , I am not adding a duplicate entry.
Regards,
Varun
For authentication, see this example https://github.com/strongloop/loopback-example-access-control.
As for the authentication token, you can set it in the query string of the request, like http://localhost:3000/api/your-model?access_token=TOKEN