I am using RESTEasy Proxy Framework to call my Rest-Services. I would like to use preemptive authentication with the proxy framework.
Thats my current Code:
public void callSomeService() throws Exception {
RegisterBuiltin.register(ResteasyProviderFactory.getInstance());
DefaultHttpClient client = new DefaultHttpClient();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(
USERNAME, PASSWORD);
AuthScope authscope = new AuthScope(AuthScope.ANY_HOST,
AuthScope.ANY_PORT, AuthScope.ANY_REALM);
client.getCredentialsProvider().setCredentials(authscope, credentials);
ApacheHttpClient4Executor executer = new ApacheHttpClient4Executor(client);
dummyResource = ProxyFactory.create(DummyResource.class,
"http://localhost:8888/myapp/rest/", executer);
// Do some calls here
}
When I monitor the traffic of my application, the Rest-Service gets called twice:
First the client receives an 401 Error (UNAUTHORIZED)
In the second request there is the Authorization Header added and everything works
fine.
What I actually want to do is that the Authorization Header is already added in the first request! How can I do that?
I am using RESTEasy 2.3.5! I also read the documentation (http://docs.jboss.org/resteasy/docs/2.3.5.Final/userguide/html_single/index.html#transport_layer) where is an example given for preemptive authentication, which actually doesnt work, because of this code:
BasicScheme basicAuth = new BasicScheme();
authCache.put("com.bluemonkeydiamond.sippycups", basicAuth);
You're right, the example in the documentation does not compile. Try replacing the string "com.bluemonkeydiamond.sippycups" with an instance of HttpHost. The HttpHost class has several constructors so be sure to look at the JavaDocs. The simplest constructor takes a string. For example,
BasicScheme basicAuth = new BasicScheme();
authCache.put(new HttpHost("com.bluemonkeydiamond.sippycups"), basicAuth);
Related
I am trying to call a SOAP RPC style web service and getting the following error:
Exception in thread "main" com.sun.xml.internal.ws.client.ClientTransportException: The server sent HTTP status code 302:
This is a https web service and I have imported the certificate into cacerts thru browser but getting same result. Please note that, I can consume a REST webservice from the same machine without importing the certificate.
What I am missing when calling a SOAP service? Is it my client issue or something need to be done on the server side. I have access to the server.
HTTP status code 302 is a redirect, and so is unlikely due to a certificate problem. My initial guess is that you need to add a / (or remove it) from your URL. Some http server frameworks will redirect when a resource does not end in a /, so, instead of:
GET /myRpcEndpoint
Try
GET /myRpcEndpoint/
The other possibility is that this resource requires authentication and the server is redirecting you to a login page. If you want to know what is going on (and not guess), take a look a the the response headers for the 302. There will be a Location header telling you where the server wants you to go instead.
Had a similar issue where client code would receive a HTTP 302 error code when communicating with https and would work fine when communicating with http. In client code,you might need to specify the endpoint address on the request context using the BindingProvider.ENDPOINT_ADDRESS_PROPERTY property. Following the JAX-WS paradigm, the example below should work.
Please note that only the BindingProvider.ENDPOINT_ADDRESS_PROPERTY needs to be defined, the rest of your code should remain the same.
public static void main(String args[]) throws {
ObjectFactory factory = new ObjectFactory();
GetProducts_Service service = new GetProducts_Service();
GetProducts getProducts = service.getGetProductsPort();
final BindingProvider getProductsBP = (BindingProvider) getProducts;
getProductsBP.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
"https://example.server.net/ExampleServicesWar/GetProducts");
GetProductsRequest request = factory.createGetProductsRequest();
GetProductsResponse response=getProducts.getProducts(request);
List<Product> products=response.getProducts();
}
All you have to is to use correct end point url
((BindingProvider)port).getRequestContext().put(BindingProvider.
ENDPOINT_ADDRESS_PROPERTY, "https://yourservice");
Need to import at the top:
import javax.xml.ws.BindingProvider;
port is Method call:
full source:
private static String getApplicationStatus(java.lang.String remoteAccessKey, java.lang.Integer responseId) {
net.quotit.oes._2010.ws.applicationstatusupdate.OASStatusUpdateService service = new net.quotit.oes._2010.ws.applicationstatusupdate.OASStatusUpdateService();
net.quotit.oes._2010.ws.applicationstatusupdate.IApplicationStatusUpdate port = service.getStatusUpdate();
((BindingProvider)port).getRequestContext().put(BindingProvider.
ENDPOINT_ADDRESS_PROPERTY, "https://servicename/basic");
return port.getApplicationStatus(remoteAccessKey, responseId);
}
I currently have a SOAP web service and I am trying to access it's endpoint but I keep getting this error:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<soap:Fault>
<faultcode>soap:Server</faultcode>
<faultstring>
No such operation: (HTTP GET PATH_INFO: /camel-example-reportincident/webservices/incident)
</faultstring>
</soap:Fault>
</soap:Body>
</soap:Envelope>
UNIT TEST
package org.apache.camel.example.reportincident;
import junit.framework.TestCase;
import org.apache.camel.CamelContext;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.jvnet.mock_javamail.Mailbox;
/**
* Unit test of our routes
*/
public class ReportIncidentRoutesTest extends TestCase {
private CamelContext camel;
// should be the same address as we have in our route
private static String ADDRESS = "cxf://http://localhost:8080/camel-example-reportincident/webservices/incident"
+ "?serviceClass=org.apache.camel.example.reportincident.ReportIncidentEndpoint"
+ "&wsdlURL=report_incident.wsdl";
protected void startCamel() throws Exception {
camel = new DefaultCamelContext();
camel.addRoutes(new ReportIncidentRoutes());
camel.start();
}
protected static ReportIncidentEndpoint createCXFClient() {
// we use CXF to create a client for us as its easier than JAXWS and works
JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
factory.setServiceClass(ReportIncidentEndpoint.class);
factory.setAddress(ADDRESS);
return (ReportIncidentEndpoint) factory.create();
}
public void testRendportIncident() throws Exception {
// start camel
startCamel();
// assert mailbox is empty before starting
Mailbox inbox = Mailbox.get("incident#mycompany.com");
assertEquals("Should not have mails", 0, inbox.size());
// create input parameter
InputReportIncident input = new InputReportIncident();
input.setIncidentId("123");
input.setIncidentDate("2008-08-18");
input.setGivenName("Claus");
input.setFamilyName("Ibsen");
input.setSummary("Bla");
input.setDetails("Bla bla");
input.setEmail("davsclaus#apache.org");
input.setPhone("0045 2962 7576");
// create the webservice client and send the request
ReportIncidentEndpoint client = createCXFClient();
OutputReportIncident out = client.reportIncident(input);
// assert we got a OK back
assertEquals("0", out.getCode());
// let some time pass to allow Camel to pickup the file and send it as an email
Thread.sleep(3000);
// assert mail box
assertEquals("Should have got 1 mail", 1, inbox.size());
// stop camel
camel.stop();
}
}
I am attempting to use CFX endpoint along with my camel routing and when I am putting the endpoint address in the route and then unit testing it I am getting a "No endpoint could be found for: //path/to/endpoint".
I am assuming that the fact that I am getting an error when I try to access the endpoint url is the issue but I do not even know where to begin on figuring out how to fix it.
When I hit my webservice on SOAP UI it runs fine as well. Any help would be greatly appreciated, and I can provide any info that is needed.
Typically, SOAP services are exposed over HTTP using the POST operation. You seem to be trying to access the service using the GET operation.
I am not sure how you try to invoke the service in your unit test, but you need to make sure it's a HTTP/POST call. If you are using plain HTTP, then you could set a header before invoking the HTTP component.
.setHeader(Exchange.HTTP_METHOD, constant("POST"))
Show your unit test for more detailed input.
#grep
I see this post as bit old, but still will try to answer if anyone else with similar problem is able to. Well, I had the same isssue and wondered what were the reason s behind those. here are the two steps that i tried and fixed up the issue. make sure you are able to access the wsdl in browser.
Close the SOAPUI, delete the soapui_workspace.xml created in user folder under C:/users.
Restart the Soap_ui and open up preferences>Proxy setting.
Change from automatic to None.
Create new project.
This did solved my issue and got the response from webservice in SOAPUI.
Actually I am trying to add items in a share point List from a windows application. It all goes fine when I added the web reference and the able to get the all the offerings listed for Lists.asmx.
When I execute my program and try to call listServiceObj.GetListAndview("Customers","");
It gives me error "The request failed with HTTP status 401: Unauthorized" . Please note that at this time my credentials and url of the service reference were;
SpListService.Lists spListService = new SpListService.Lists();
spListService.Credentials = System.Net.CredentialCache.DefaultCredentials;
spListService.Url = "http://localhost/_vti_bin/Lists.asmx";
XmlNode customerListView = spListService.GetListAndView("Customers", "");
Then I Changed the above code to ;
SpListService.Lists spListService = new SpListService.Lists();
spListService.Credentials = System.Net.CredentialCache.DefaultCredentials;
spListService.Url = "http://<PC-Name>/sites/Home/_vti_bin/Lists.asmx";
XmlNode customerListView = spListService.GetListAndView("Customers", "");
then I recieved the following error;
"Exception of type 'Microsoft.SharePoint.SoapServer.SoapServerException' was thrown."
I have made the logged in user in the group of full controll. also the member of the Administrator group.. but same result....
Also please note that when try and access "http://localhost/" or "http:///" it gives me access denied page of SP2010.... instead I have to write "http:///sites/Home/SitePages/Home.aspx" to open my team site collection
I really stuck in to this .... would be really pleased to have some solution to this problem of mine...... Thanks in advance
MJay
I had a similar problem when I implemented my first SharePoint lists Web Service client. The reason was that the autogenerated client class actually introduced itself as a Mozilla web browser by default! The SharePoint server did not allow basic authentication for browsers so the client was actually redirected to firewall login page.
I suggest you to inherit another class from the Lists class and do the following:
Set another user agent value in constructor.
Set the "preauthenticate" property to true. This should force the client to send the credentials in the first request, not only after they have been asked for.
If necessary, try giving the credentials explicitly.
See the example below.
public class CustomizedLists : Lists
{
public CustomizedLists() : base()
{
this.UserAgent = "Some SharePoint client";
this.PreAuthenticate = true;
System.Net.ICredentials creds = new System.Net.NetworkCredential("user", "pwd");
this.Credentials = creds.GetCredential(uri, "Basic");
}
}
I am badly stuck with a SOAP based integration using Axis2 framework for generation of client stubs from the Server WSDL. The scenario is as follows :
There is always a login API call first, which gives a Success response in SOAP body and Temporary Redirect in HTTP header. Also provides a URL which contains the session ID in the Location field of HTTP Header.
The next API call is required to be made at this redirect location. IN THE SAME TCP CONNECTION, for getting a proper response.
Now, the problem is, as a part of Webservice implementation using Axis2 generated stubs, I need to reload this redirect URL and re-instantiate it as --- "stub=new Stub(newurl)"
As soon as this is done, it creates a new TCP connection and so, the next request gives the response as "session ID invalid" because it goes out-of-sync with login API.
I have tried everything mentioned as a solution in this forum and nothing is working out.
For e.g --
MultiThreadedHttpConnectionManager httpConnectionManager = new MultiThreadedHttpConnectionManager();
HttpClient httpClient = new HttpClient(httpConnectionManager);
ServiceClient serviceClient = stub._getServiceClient();
Options opts = stub._getServiceClient().getOptions();
opts.setTo(new EndpointReference(prop.getProperty("target_end_point_url")));
opts.setProperty(HTTPConstants.REUSE_HTTP_CLIENT, Constants.VALUE_TRUE);
opts.setProperty(HTTPConstants.CACHED_HTTP_CLIENT, httpClient);
serviceClient.setOptions(opts);
stub._setServiceClient(serviceClient);
Similarly, I have tried many other options too. But it's not helpful at all.
Faced exactly the same issue.
Following steps solved the issue.
1. Using HttpClient, perform login. Don't use stub object to perform login.
2. Use the Location Header URL, to create new stub object i.e. stub = new Stub(locationURL). (Your existing options setting should be retained.)
3. There is a default timeout, by which server disconnects the TCP connection. In my case it was 50 seconds. Hence as soon as i performed login in step 1, i execute a timer every 40 seconds, to send an empty requests to new Location URL using HeadMethod of same HttpClient object.
I'm behind ISA Server Proxy and I need to call a web service. Given its wsdl I've created proxies (using Add Service Reference command) and have tried to call the service, but it raised an exception telling me that proxy authorization is required. After some research I've found a solution to my problem
var webproxy = new WebProxy(new Uri("http://<address>:<port>").ToString(), true, new string[]
{
})
{
Credentials = networkCredentials,
BypassProxyOnLocal = false
};
WebRequest.DefaultWebProxy = webproxy;
After this piece of code I'm able to call web service. But as I've read here by default DefaultWebProxy uses the same settings as set in IE. However WebRequest.DefaultWebProxy.Credentials is null and I'm unable to pass thru the proxy. Why?
I've was also same boat. The last answer on this post helped me.
How do I determine (elegantly) if proxy authentication is required in C# winforms app
Especially.
//HACK: add proxy
IWebProxy proxy = WebRequest.GetSystemWebProxy();
proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
req.Proxy = proxy;
req.PreAuthenticate = true;
//HACK: end add proxy