I am having problem with jax-ws making it work if the server return 301 on http to https. I got an exception, and after debugging it with charles it seems that the redirect doesn't work. I also noticed that there is some trick for http to https[*], but i am not sure if it still apply to java8
That's the pseudo-code that i would like to use with a dirty fix that i found online
TestImplService service = new TestImplService();
Test test = service.getTestImplPort();
Map<String, Object> tmp = ((BindingProvider) test).getRequestContext();
/*dirty fix*/
tmp.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, tmp.get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY).toString().replace("http:", "https:")
);
test.dosomething();
Replacing http with https work, but i am not 100% sure that's the correct way.
Let's suppose that the server decide to stop to support https, disable the 301 for http, then my fix won't work anymore.
Can i force the follow redirect in another way?
[*] https://docs.oracle.com/javase/6/docs/technotes/guides/deployment/deployment-guide/upgrade-guide/article-17.html
BindingProvider class BindingProvider.ENDPOINT_ADDRESS_PROPERTY property is usable for change endpoint URL; Sometimes HTTPS connection ended with network switches/routers. Therefor application server cannot realize the path of https.
service = new ....(url, SERVICE_NAME);
port = service.get...BasicHttpEndpoint();
BindingProvider provider = ((BindingProvider) port);
Map<String, Object> map = provider.getRequestContext();
String current = map.get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY).toString();
map.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, current.replace("http:", "https:"));
Related
I'm using Restlet 2.3.2
I'd like to run a Restlet server with both HTTP and HTTPS protocols, but I'd like to attach a different restlet to each one. For exemple, restletUnsecure to HTTP but restletSecure to HTTPS. Actualy, attaching only one restlet to the path /test works properly.
I tried putting the scheme in the URI while attaching, like this, but this does not work (I get a page not found with my browser) :
Server server = component.getServers().add(Protocol.HTTPS, 8443);
component.getServers().add(Protocol.HTTP, 8080);
[...]
component.getDefaultHost().attach("https://localhost:8443/test", restletSecure);
component.getDefaultHost().attach("http://localhost:8080/test", restletUnsecure);
How can I achieve this ?
I think that you should define specific virtual hosts HTTP and HTTPS requests, as described below:
Component component = (...)
// HTTPS
VirtualHost hostHttps
= new VirtualHost(component.getContext());
component.getHosts().add(hostHttps);
hostHttps.setHostScheme("https");
Restlet restletSecure = (...)
hostHttps.attachDefault(restletSecure);
// HTTP
VirtualHost hostHttp
= new VirtualHost(component.getContext());
component.getHosts().add(hostHttp);
hostHttp.setHostScheme("http");
Restlet restletUnsecure = (...)
hostHttp.attachDefault(restletUnsecure);
Hope it helps you,
Thierry
I created the jar from the WSDL for my client using the wsdl2java command. Now, I need to know how I can authenticate my client in order to complete an operation?
I am using CXF 2.7.16. I created my service using the generated class MyApp_Service, I am struggling with this. Isn't there a simple way to tell my client the credentials it should use to gain access to the web service?
I read about the Spring configuration, however I am unable to figure out if it applies to my case and how if yes. I tried to cast the MyApp_Service class to BindingProvider in order to use the method which consist to put the USERNAME and PASSWORD properties in the context with a value. However, MyApp_Service cannot be cast to BindingProvider.
This is my first web service client application ever. So, any help will be welcomed.
Update 2015-05-28: I tried to define the AuthenticationPolicy but is seems not working. Here is the code:
Client client = JaxWsDynamicClientFactory.newInstance().createClient(wsdlUrl);
ClientImpl clt = (ClientImpl) client;
HTTPConduit cc = (HTTPConduit) clt.getConduit();
org.apache.cxf.configuration.security.ObjectFactory secOF = new org.apache.cxf.configuration.security.ObjectFactory();
AuthorizationPolicy ap = secOF.createAuthorizationPolicy();
ap.setUserName(usagerWS);
ap.setPassword(mdpWS);
ap.setAuthorizationType("Basic");
cc.setAuthorization(ap);
Sniffing with WireShark, the Authorization header is clearly missing in the HTTP request.
What is missing?
Problem solved, here is the solution:
MyApp_Service service = new MyApp_Service(wsdlUrl, new QName(namespace, serviceName));
MyApp port = service.getMyApp();
// Set credentials
Map<String, Object> reqCtxt = ((javax.xml.ws.BindingProvider) port).getRequestContext();
reqCtxt.put(javax.xml.ws.BindingProvider.USERNAME_PROPERTY, username);
reqCtxt.put(javax.xml.ws.BindingProvider.PASSWORD_PROPERTY, password);
No more usage of the dynamic client. Only the classes generated with wsdl2java are used.
Respected Experts,
I am trying to access a web service that requires basic authentication. I am able to access using the CXF's JaxWsDynamicClientFactory. The code piece for auth looks like:
JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
Client client = dcf.createClient(ID_WSDL);
HTTPConduit conduit= (HTTPConduit) client.getConduit();
AuthorizationPolicy authorization = conduit.getAuthorization();
authorization.setUserName(USERNAME);
authorization.setPassword(PWD);
conduit.setAuthorization(authorization);
However, when I try to use Camel's CXF component to access the same Web Service I get 401 Unauthorized error, since Camel is not sending the authentication information to the Web Service.
My route looks like:
from("file://c:/test?fileName=request.txt&noop=true").routeId("myrouteId")
.process(processor)
.to(cxf)
.to("log:{body}");
In my processor, I am setting the credentials as follows:
Map<String, Object> properties = new HashMap<String, Object>();
AuthorizationPolicy authPolicy = new AuthorizationPolicy();
authPolicy.setAuthorizationType(HttpAuthHeader.AUTH_TYPE_BASIC);
authPolicy.setUserName(USERNAME);
authPolicy.setPassword(PWD);
properties.put("org.apache.cxf.configuration.security.AuthorizationPolicy", authPolicy);
myEndpoint.setProperties(properties);
myEndpoint is CXFEndpoint, retrieved from Exchange.
Am I missing something or something wrong here.
There is a similar question. I had raised my doubt there as a answer since I was not able to comment. However, my answer has been deleted. So, I am raising a fresh question in a hope that I will get some direction to move forward on this.
Thks & brgds
With Willem's help, was able to make this working. The authentication credentials need to passed to the CXF Endpoint in the Route Builder rather than in the Processor. This is as explained by Williem on Camel forum:
If you set the cxfEndpoint property in a processor, it’s a setting of runtime.
As the CxfProducer is created during the camel context start the route, the cxfEndpoint’s property is >not updated.
So, to fix this add the following code to the Route Builder:
Map<String, Object> properties = new HashMap<String, Object>();
AuthorizationPolicy authPolicy = new AuthorizationPolicy();
authPolicy.setAuthorizationType(HttpAuthHeader.AUTH_TYPE_BASIC);
authPolicy.setUserName(USERNAME);
authPolicy.setPassword(PWD);
authPolicy.setAuthorization("true");
//properties.put(AuthorizationPolicy.class.getName(), authPolicy);
properties.put("org.apache.cxf.configuration.security.AuthorizationPolicy", authPolicy);
CxfEndpoint myCxfEp = (CxfEndpoint)getContext().getEndpoint("cxf://");
myCxfEp.setProperties(properties);
Also, version 2.12.3 of Apache Camel is introducing username and password options for basic authentication.
I want to add authentication header to my request. I'm using DefaultHttpClient from Apache httpclient 4.0.
I found that's done this way:
URI uri = new URI("http://www.bla.bla/folder/");
String host = uri.getHost();
int port = uri.getPort();
httpClient.getCredentialsProvider().setCredentials(
new AuthScope(host, port, AuthScope.ANY_SCHEME),
new UsernamePasswordCredentials("myuser", "mypassword")
);
This is executed and even with the debugger I see some credentials variable of the httpClient are set at the moment of doing the request. But I inspect web traffic with Charles and there's no authentication header.
Content of vars:
host: www.bla.bla
port: -1
Btw. I enabled Charles as a proxy to see the headers of the request, with:
HttpHost proxy = new HttpHost("127.0.0.1", 8888, "http");
httpParameters.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
I think that should not be altering my headers, would make no sense for webproxy... anyways if I disable the proxy stuff it also doesn't work (although I can't see the content of the header but I suppose it's the same reason).
Also tried using a request interceptor like described in Softhinker.com's post here: How can I send HTTP Basic Authentication headers in Android?
And I get exactly the same request, without authentification header.
What am I doing wrong?
Thanks in advance.
I got it working setting the header "manually" in the request.
request.setHeader(new BasicHeader("Authorization", authstring));
I use Netbeans to generate web service client code, client-style JAX-WS, so i can invoke a web service API.
However, when I invoke the web service API, I get the exception:
com.sun.xml.internal.ws.client.ClientTransportException: The server sent HTTP status code 307: Temporary Redirect
Why do I get this? What is the workaround? I know the problem isn't with the web service itself, because I can get responses fine via soapUI and .Net.
Faced the same problem about a month ago.
Web service client classes were generated using Apache CXF and web service returned HTTP
status 307, which led to the same exception.
Invocation of the same web service method using soapUI with property Follow Redirects set to true was successful and returned needed data.
After googling awhile, it looked like there is no property to enable following redirects in the JAX-WS for this.
So, below is the code which is currently working, though I'm not sure it is compliant with any standards:
Supposing generated client classes looks like:
// generated service class
public class MyWebServiceClient extends javax.xml.ws.Service {
// ...
private final QName portName = "...";
// ...
public RetrieveMyObjects getRetrieveMyObjects() {
return super.getPort(portName, RetrieveMyObject.class);
}
// ...
}
// generated port interface
// annotations here
public interface RetrieveMyObjects {
// annotations here
List<MyObject> getAll();
}
Now, upon executing following code:
MyWebServiceClient wsClient = new MyWebServiceClient("wsdl/location/url/here.wsdl");
RetrieveMyObjectsPort retrieveMyObjectsPort = wsClient.getRetrieveMyObjects();
wsClient should return instance which is both instance of RetrieveMyObjects & javax.xml.ws.BindingProvider interfaces. It is not stated anywhere on the surface of JAX-WS, but it seems that a lot of code is based on that fact. One can re-assure him\herself by executing something like:
if(!(retrieveMyObjectsPort instanceof javax.xml.ws.BindingProvider)) {
throw new RuntimeException("retrieveMyObjectsPort is not instance of " + BindingProvider.class + ". Redirect following as well as authentication is not possible");
}
Now, when we are sure that retrieveMyObjectsPort is instance of javax.xml.ws.BindingProvider we can send plain HTTP POST request to it, simulating SOAP request (though it looks incredibly incorrect & ugly, but this works in my case and I didn't find anything better while googling) and check whether web service will send redirect status as a response:
// defined somewhere before
private static void checkRedirect(final Logger logger, final BindingProvider bindingProvider) {
try {
final URL url = new URL((String) bindingProvider.getRequestContext().get(ENDPOINT_ADDRESS_PROPERTY));
logger.trace("Checking WS redirect: sending plain POST request to {}", url);
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setInstanceFollowRedirects(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "text/html; charset='UTF-8'");
connection.setDoOutput(true);
if(connection.getResponseCode() == 307) {
final String redirectToUrl = connection.getHeaderField("location");
logger.trace("Checking WS redirect: setting new endpoint url, plain POST request was redirected with status {} to {}", connection.getResponseCode(), redirectToUrl);
bindingProvider.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, redirectToUrl);
}
} catch(final Exception e) {
logger.warn("Checking WS redirect: failed", e);
}
}
// somewhere at the application start
checkRedirect(logger, (BindingProvider) retrieveMyObjectsPort);
Now, what this method does is: it takes BindingProvider.ENDPOINT_ACCESS_PROPERTY of retrieveMyObjectsPort i.e. the url to which this port method will be sending SOAP requests and sends plain HTTP POST request as described above. Then it checks whether response status is 307 - Temporary Redirect (other statuses like 302 or 301 may also be included) and if it is, gets the URL to which web service is redirecting and sets new endpoint for the specified port.
In my case this checkRedirect method is called once for each web service port interface and then everything seems to work fine:
Redirect is checked on url like http://example.com:50678/restOfUrl
Web service redirects to url like https://example.com:43578/restOfUrl (please note that web service client authentication is present) - endpoint of a port is set to that url
Next web service requests executed via that port are successful
Disclaimer: I'm quite new to webservices and this is what I managed to achieve due to the lack of solutions for this questions, so please correct me if something is wrong here.
Hope this helps
Yes I know this post is old, but I've had similar errors, and thought maybe somebody would benefit from my solution.
the one that plagued me the most was:
com.sun.xml.ws.client.ClientTransportException: The server sent HTTP status code 200: OK
Which turns out to mean an incomplete response header. Apparently jax-ws does some kind of validation that includes validating the HTTP headers as well. And the server I was using was just sending an empty header.
It worked like a charm after adding 'application/soap+xml' to the Content-Type header.