XML RPC Header Modification with JAVA - java

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);

Related

apache cxf MultiPart request has no Content-Length header

I'm having below code to send a multipart/form-data request.
List<Attachment> multipartData = new ArrayList<>();
ContentDisposition cd1 = new ContentDisposition("form-data; name=\"file\";
filename="+fileObj.getName());
FileInputStream inputStream = new FileInputStream(fileObj);
multipartData.add(new Attachment("file",inputStream, cd1));
MultipartBody multipart = new MultipartBody(multipartData);
In my RestClient class, I'm using the below lines of code to send a POST request using JAX-RS Client object
if ("POST".equals(method)) {
response = this.client.getBuilder().post(Entity.entity(entity,MediaType.MULTIPART_FORM_DATA));
I checked the HTTP request body using Wiremock and is as below:
Transfer-Encoding: [chunked]
Accept: [*/*]
Cache-Control: [no-cache]
User-Agent: [Apache-CXF/3.2.5]
Connection: [keep-alive]
Host: [127.0.0.1:9990]
Pragma: [no-cache]
Content-Type: [multipart/form-data; boundary="uuid:04b491f5-50de-4f4f-b7c0-cd745136d3d1"]
--uuid:04b491f5-50de-4f4f-b7c0-cd745136d3d1
Content-Type: application/octet-stream
Content-Transfer-Encoding: binary
Content-ID: <file>
Content-Disposition: form-data; name="file"; filename=sample.txt
<File content goes here>
I want to know how the content-length header is missing in the request payload. Is there any way to set the content-length header to the request?
Please help me.
I used the apache cxf WebClient to unset the transfer encoding as chunked.
if ("POST".equals(method)) {
Invocation.Builder builder = this.client.getBuilder();
WebClient.getConfig(builder).getHttpConduit().getClient().setAllowChunking(false);
response = builder.post(Entity.entity(entity,MediaType.MULTIPART_FORM_DATA));
}
With this, the client is able to send the request with content-length header.

java - HttpClient doesn't authenticate with NTLM

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.

Jax-WS with NTLM authentification

As I read Jax-ws can authenticate with NTLM, but I have a problem;
First of all I create MyAuthenticator java class as describe in java documentation(see:
http://docs.oracle.com/javase/7/docs/technotes/guides/net/http-auth.html).
when I try to connect with soapUI everything is Ok, see request header:
Request Headers Value
(Request-Line) POST /Online/OnlineServices.asmx HTTP/1.1
Content-Type text/xml;charset=UTF-8
SOAPAction "http://CTL.COM/OnlineServices/AcquireTicket"
Host 172.22.2.144:8000
Connection Keep-Alive
User-Agent Apache-HttpClient/4.1.1 (java 1.5)
Authorization NTLM TlRMTVNTUAADAAAAGAAYAEAAAACgAKAAWAAAAAYABgD4AAAAGAAYAP4AAAAMAAwAFgEAAAAAAAAiAQAA
Accept-Encoding gzip, deflate
Content-Length 702
when I try to connect with java, I got 500 Internal server error, see header:
Request Headers Value
(Request-Line) POST /Online/OnlineServices.asmx HTTP/1.1
SOAPAction "http://CTL.COM/OnlineServices/AcquireTicket"
Accept text/xml, multipart/related, text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Content-Type text/xml;charset="utf-8"
User-Agent JAX-WS RI 2.1.4-b01-
Host 172.22.2.144:8000
Connection keep-alive
Authorization NTLM TlRMTVNTUAADAAAAGAAYAIwAAAD8APwApAAAAAYABgBYAAAAIgAiAF4AAAAMAAwAgAAAAAAAAACgAQAABYKIogoAOTgAAAAP5/lqdc43ElnLlEh5ASEkQlUARgBDAGUAdgBnAGUAbgBpAC4AbwByAG0AbwB0AHMAYQBkAHoAZQBQAEMALQAyADMAMQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABXZ
Accept-Encoding gzip, deflate
Content-Length 443
this is my code :
Authenticator.setDefault(new MyAuthenticator(domain + "\\kuser","kpass"));
OnlineServicesSoap onlineServicesSoap = new OnlineServices(url,qName).getOnlineServicesSoap();
Map<String, List<String>> headers = new HashMap<String, List<String>>(); headers.put("Content-Type", Collections.singletonList("text/xml;charset=UTF-8"));
headers.put("Accept-Encoding", Collections.singletonList("gzip, deflate"));
((BindingProvider)onlineServicesSoap).getRequestContext().put(MessageContext.HTTP_REQUEST_HEADERS, headers);
try {
AcquireTicketResponse acquireTicketResponse =
onlineServicesSoap.acquireTicket(acqTicket);
} catch (RuntimeException ex) {
System.out.println(ex.getMessage() + ex.getCause());
}
I searched a lot and found some posts suggesting to do NTLM authentication but I couldn't to connect.. I don't want to use axis implementation

OAuth2 oltu client

I'm building my oauth2-protecet webservice, and a client. For webservice I used spring security implementation, and used this as example. For client I'm trying out apache oltu library. Here's my snippet:
OAuthClientRequest request = OAuthClientRequest.tokenLocation
("http://localhost:8080/oauth/token")
.setGrantType(GrantType.CLIENT_CREDENTIALS)
.setClientId("clientapp")
.setClientSecret("123456")
.buildHeaderMessage();
OAuthAccessTokenResponse oAuthResponse = cli.accessToken(request);
System.out.println(oAuthResponse.getAccessToken());
It does not work. While this
curl -X POST -vu clientapp:123456 --data "grant_type=client_credentials&client_secret=123456&client_id=clientapp" http://localhost:8080/oauth/token
works perfectly well. Here's the curl request:
POST /oauth/token HTTP/1.1
Authorization: Basic Y2xpZW50YXBwOjEyMzQ1Ng==
User-Agent: curl/7.35.0
Host: localhost:8080
Accept: */*
Content-Length: 70
Content-Type: application/x-www-form-urlencoded
grant_type=client_credentials&client_secret=123456&client_id=clientapp
as you can see, I used Basic authentication with curl and it worked(even though suggested authentication type is Bearer).
And here's oltu packet:
POST /oauth/token HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Authorization: Bearer client_credentials123456clientapp
User-Agent: Java/1.8.0_51
Host: localhost:8080
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive
Content-Length: 4
null
I'm nor sure how bearer authorization is supposed to work, but this packet looks all wrong.
I also tried to use buildBodyMessage() and buildQueryMessage() instead of buildHeaderessage() as was suggested in this post, but it's no good either.
This line doesnt look very healthy:
Authorization: Bearer client_credentials123456clientapp
I created a test server with Oltu, basically a servlet:
OAuthResponse oauthResponse = OAuthASResponse
.tokenResponse(HttpServletResponse.SC_OK)
.setAccessToken(accessToken)
.setExpiresIn(Integer.toString(expires))
.setRefreshToken(refreshToken)
.buildJSONMessage();
response.setStatus(oauthResponse.getResponseStatus());
response.setContentType("application/json");
And for the client I got:
OAuthClientRequest request = OAuthClientRequest
.tokenLocation("http://localhost:8083/OltuServer/token")
.setGrantType(GrantType.CLIENT_CREDENTIALS)
.setClientId("clientapp")
.setClientSecret("123456")
.buildQueryMessage();
OAuthAccessTokenResponse oAuthResponse = oAuthClient.accessToken(request);
System.out.println(oAuthResponse.getAccessToken());
The main difference from your code is buildQueryMessage(). Using buildHeaderMessage() I get an exception on the server
OAuthProblemException {error='invalid_request', description='Missing grant_type parameter value' ... }
But I see that Oltu is at version 1.0.1 now while I've been testing on 1.0.0. That version might behave different.
The following appeared to work for me:
OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
OAuthClientRequest bearerClientRequest = OAuthClientRequest.tokenLocation("http://localhost/rest/auth")
.setUsername("userid")
.setPassword("Password01")
.buildQueryMessage();
bearerClientRequest.setHeader(OAuth.HeaderType.CONTENT_TYPE, "multipart/form-data");
OAuthResourceResponse resourceResponse = oAuthClient.resource(bearerClientRequest, OAuth.HttpMethod.POST, OAuthResourceResponse.class);

Jersey Client set content-type header as text/plain

Using jersey client sending HTTP request. Content-Type header is automatically set as "application/json" (as a nature), but i want to changing "content-type" header with "text/plain" regardless of any specification, standards etc. Jersey version is 2.4.1.
Code
String target = "http://192.168.1.2:10000";
String path = "test3";
Client c = ClientBuilder.newClient ();
WebTarget target = c.target (target).path (path);
Entity<SubscriberBean> json = Entity.json (subscriber);
Builder request = target.request ();
String response = request.post(json, String.class);
Request
POST /test3 HTTP/1.1
Accept: text/html
Content-Type: application/json
User-Agent: Jersey/2.4.1 (HttpUrlConnection 1.6.0_17)
Host: 192.168.1.2:10000
Connection: keep-alive
Content-Length: 278
///**** Some json data ***///
instead of
request.post(json, String.class);
try to use
request.type(MediaType.TEXT_PLAIN).post(json, String.class);
Use Entity.text(entityData) or Entity.entity(entityData, mediaType) methods instead of Entity.json() in your example.

Categories