Home » Microsoft Technologies

Connect to web service with Java


Has anyone tried to consume an MS CRM 4 webservice via Java?  We are trying to connect to the /MSCrmServices/2007/CrmService.asmx page and we receive error 401s.  The IIS log file shows this:

2008-09-25 17:51:59 W3SVC1 POST /MSCrmServices/2007/CrmService.asmx - 80 mydomain\myusername Java/1.6.0_07 401 5 64

I know that if I open the web service page with a browser I get a 302 which is a redirect:

2008-09-25 17:55:25 W3SVC1 GET /MSCrmServices/2007/CrmService.asmx - 80 mydomain\myusername Mozilla/4.0+(compatible;+MSIE+7.0;+Windows+NT+5.1;+.NET+CLR+1.1.4322;+.NET+CLR+2.0.50727;+MS-RTC+LM+8) 302 0 0

Has anyone successfully sent user credentials to CRM?



12 Answers Found


Answer 1

I've not tried connecting with Java, but I have tried connecting with .Net techniques from outwith the domain on which the CRM server resides, and got much the same results as you're describing above. Is your Java app attempting to connect  with the Web Services as a user on a domain that is different from the CRM Server's domain?


Answer 2

I have done some more tests and determined that we had two issues.

The first is our authentication method.  We had to use the Java security libraries to communicate with the web  server using SPNEGO authentication. 

The second problem was with our SOAP request.  This problem was very hard to nail down but we were using a sample SOAP message from crm  4 Unleashed.  When we posted this message to the crmservice.asmx page  we kept receiving an error  500 error.  Eventually we used a .NET application we wrote to create a contact using the web service.  I setup a packet sniffer on the CRM server and monitored the actual message sent.  It turns out that CRM 4 Unleashed did not provide a valid SOAP message for CRM.  When I took the message I obtained from the packet sniff and sent it to the server the contact was created. 

Anyways this was a heck of a problem.  Microsoft and book writers should do a better job explaining the proper SOAP message format as well as provide more information on how to connect  to the web services with non-.NET clients.  Web services are *supposed* to be client neutral.


Answer 3

You receive  these errors, because you are not using an NTLM authentication mode. In order to connect  to CRM web  services from Java, look for Axis2 framework (http://ws.apache.org/axis2/) that supports the NTLM authentication and then in your Java code, provide your credentials:

HttpTransportProperties.NTLMAuthentication ntlmAuthentication = new HttpTransportProperties().new NTLMAuthentication();

I hope that helps,



Answer 4

Yes, one of the problems was due to NTLM authentication but I fixed this as stated in my previous post.  I am using Sun's security library to connect  to IIS.  The second problem was with the format of the SOAP request.  CRM Unleashed was incorrect in their example.


Answer 5

Is there any way to access MS CRM WS via JAX-WS rather then via Axis2? I generated WS stubs in NetBeans using JAX-WS style. When I'm trying to access CRM web  service i'm getting next error:

com.sun.xml.ws.client.ClientTransportException: request requires HTTP authentication: Unauthorized

see my code below:

CrmService service  = new CrmService();
CrmServiceSoap port = service.getCrmServiceSoap12();
java.net.Authenticator.setDefault(new MyAuthenticator("user@company.com", "pwd"));
WSBindingProvider bp = (WSBindingProvider) port;
bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "https://oursite/MSCrmServices/2007/CrmService.asmx");
Retrieve parameters = new Retrieve();
RetrieveResponse result = port.retrieve(parameters);

class MyAuthenticator
      extends java.net.Authenticator
    String user;
    String password;

    public MyAuthenticator(String user, String password)
      this.user = user;
      this.password = password;

    protected java.net.PasswordAuthentication getPasswordAuthentication()
      return new java.net.PasswordAuthentication(user, password.toCharArray());

Plese, help me, what I'm doing wrong
Thanks in advance


Answer 6

Probably just your authentication method.  You can try changing the CRM security to Basic just to verify this.


Answer 7

How and where can I change the CRM security to Basic on MS Dynamics CRM Online?

Answer 8

Sorry I didnt realize you were using CRM Online.  You should find out what kind of authentication CRM Online uses (probably spnego) and then use the correct java  security library.  Look at my posts at the top of this thread for more info.


Answer 9

I ve succesfully connected to crm  Dynamics 4.0 Web service  using Axis2 (Soap1.2, NTLM Auth) and did a retrieveMultiple

My code::

//you ll need this..  
import com.microsoft.schemas.crm._2007.coretypes.CrmAuthenticationToken;  
public class TestCRM {  
private static String endpointURL = "http://server:port/MSCrmServices/2007/CrmService.asmx";  
private static String userName = "username";  
private static String password = "password";  
private static String host = "server";  
private static int portport = port;  
//To make sure you are using the correct domain open ie and try to reach the service. The same domain you entered there is needed here  
private static String domain = "DOMAIN";   
private static String orgName = "THIS_IS_REQUIRED"; //this does the work....  
public static void main(String[] args) {  
    CrmServiceStub stub;  
    try {  
stub = new CrmServiceStub(endpointURL);  
        RetrieveMultipleDocument rmd = RetrieveMultipleDocument.Factory.newInstance();  
        RetrieveMultiple rm = RetrieveMultiple.Factory.newInstance();  
        QueryExpression query = QueryExpression.Factory.newInstance();  
        //Now this is required. Without it all i got was 401s errors  
        CrmAuthenticationTokenDocument catd = CrmAuthenticationTokenDocument.Factory.newInstance();  
        CrmAuthenticationToken token = CrmAuthenticationToken.Factory.newInstance();  
        boolean fetchNext = true;  
            RetrieveMultipleResponseDocument rmrd = stub.RetrieveMultiple(rmd,  catd, null, null);  
            RetrieveMultipleResponse rmr = rmrd.getRetrieveMultipleResponse();  
            BusinessEntityCollection bec = rmr.getRetrieveMultipleResult();  
            String pagingCookie = bec.getPagingCookie();  
fetchNext = bec.getMoreRecords();  
            ArrayOfBusinessEntity aobe = bec.getBusinessEntities();  
            BusinessEntity[] myEntitiesAtLast = aobe.getBusinessEntityArray();  
            for(int i=0; i<myEntitiesAtLast.length; i++){  
                //cast to whatever you asked for...  
                ### myEntity = (###) myEntitiesAtLast[i];  
    catch (Exception e) {  
private static void setOptions(Options options){  
    HttpTransportProperties.Authenticator auth = new HttpTransportProperties.Authenticator();  
    List authSchemes = new ArrayList();  
    auth.setPreemptiveAuthentication(false); //it doesnt matter...  
    options.setProperty(HTTPConstants.AUTHENTICATE, auth);  
    options.setProperty(HTTPConstants.REUSE_HTTP_CLIENT, "true"); //i think this is good.. not required though  

Take a look here http://www.microsoft.com/communities/newsgroups/en-us/default.aspx?dg=microsoft.public.crm.developer&tid=61c3fde8-259b-49ea-b42e-b7fa26109f61&cat=&lang=&cr=&sloc=&p=1
This led me to that solution.

Hope i helped


Answer 10

Hi ,
      I am very new to CRM and webservice  . i generated  wsdl to  java  code using ecipse . but it didn't generate CrmServiceStub to make the connection so i tried this way
CrmService service  = new CrmService(); but CRMService is interface . so i can't create a instance of this also . i tried implement class but didn't help

please help on this is there any other way to generate the WSDL file  to java ? i am not sure i am missing any file ?

thanks in advance


Answer 11

Hi minos.ms , I used your code it is working for me for the retrivemultipe record . with out query condition . but i am trying to retrive the data with the query condition . i am getting axis fault . do you have sample code for this ? if you have can you please provide me . thanks a lot .

Answer 12

Dear Friends,

I am trying to connect  MSCrm thru Java client ,so I need Jars file  which contains all the necessary class.

Please send me the Jars or location of the jars where I can down load.

Thanks in advance.






Has anyone tried to consume an MS CRM 4 webservice via Java?  We are trying to connect to the /MSCrmServices/2007/CrmService.asmx page and we receive error 401s.  The IIS log file shows this:

2008-09-25 17:51:59 W3SVC1 POST /MSCrmServices/2007/CrmService.asmx - 80 mydomain\myusername Java/1.6.0_07 401 5 64

I know that if I open the web service page with a browser I get a 302 which is a redirect:

2008-09-25 17:55:25 W3SVC1 GET /MSCrmServices/2007/CrmService.asmx - 80 mydomain\myusername Mozilla/4.0+(compatible;+MSIE+7.0;+Windows+NT+5.1;+.NET+CLR+1.1.4322;+.NET+CLR+2.0.50727;+MS-RTC+LM+8) 302 0 0

Has anyone successfully sent user credentials to CRM?



Hi Folks,

I am working on a project where the WCF code calls a Java Web Service which exposes a Java OutputStream.

When this java output stream is accessed from dot net, dot net is not able to read from it (or) cast it to any of the .Net available streams like for example (System.IO.Stream) or httpresponse or httprequest streams.

Has anyone tried accessing java streams over a proxy coming from a java web service through WSDL.

The error we get is : Cannot implicitly convert ProjectName.ServiceRefName.OutputStream to System.IO.Stream





I started write java based web services using axis.jar(probably older version..NOT axis2). I am using keys. Iused wsdl2java from axis .jar to create the stub classes. below is the code and it worked fine....

   BasicHttpBinding_IGeocodeServiceStub geocodeServiceClient = (BasicHttpBinding_IGeocodeServiceStub) (new GeocodeServiceLocator()).getBasicHttpBinding_IGeocodeService();
   GeocodeRequest request = new GeocodeRequest();


Now I am ready to write ANT scripts and took axis2 instead of axis. The ant task using axis2 generate lot of other classes and does not have some of the older classes I had generated. I am getting compile errors on all my web service code.

Is there anyone out there that could post JAVA based web service code for geocode and route. I cannot resolve the compile errors.  BasicHttpBinding_IGeocodeServiceStub is no longer availble in the new set of generated classes.

Could someone explain.





Hi there,

I am trying to set up a WCF service ( needed for duplex communication with a .net client ) and a java webservice ( which will pull some string in some existing java classes ).

The idea is that I will be able to call exposed methods in the existing java classes from the .net client and call exposed .net methods from the java webservice.

I have set up my WCF service and .net client and this is working fine.

I have created a java webservice and set up the WCF service as a web reference ( I think I've set it up correctly :) )

The issue Im getting is that when I try to instantiate the WCF service to enable calls to it I recieve the following exception.

Service invocation threw an exception with message : null; Refer to the server log for more details Exceptions details : java.lang.reflect.InvocationTargetException

This is the line that is causing the exception.

org.tempuri.AdderAndCaller moo = new AdderAndCaller();

Please let me know what other information you require as I dont want to just go posting a load of irrelevant stuff.

Kind Regards




I have developed a java application, which needs to establish connection with SQL Azure (using hibernate). Using the Tomcat Solution accelarator, this java application is able to connect to SQL Azure when working in development fabric. But when I deploy the application to Azure, connectivity to SQL Azure fails. Following are the contents of the properties file which specifies the connectivity parameters:


Any trouble shooting tips which can be tried ?


Hi All,

I currently have a WSE 2.0 client that connects successfully to a Java web service and I'm trying to get a WCF client to do the same thing. I've tried basicHttpBinding, wsHttpBinding, and also customBinding with different variations with no success. I'm hoping if I post my _working_ WSE client code that someone can easily translate it to either a config or code based solution.

string _javaSignCertName = "java_messagesign_test";
string _javaSSLCertName = "*.javaWS.com"string _javaWebServiceURL = "https://javatest.javaservices.com:443/JavaServiceWS";
javaServiceWS_vs0 javaService = null;

// WSE 2.0 method
X509CertificateStore store = X509CertificateStore.LocalMachineStore(X509CertificateStore.MyStore);


// Look in the local machine store.
X509CertificateCollection col = (X509CertificateCollection)store.FindCertificateBySubjectString(_javaSignCertName);
Microsoft.Web.Services2.Security.X509.X509Certificate cert = null;
   // This sample obtains the first matching certificate from the collection.
     cert = col[0];
catch (Exception ex)
    thrownew Exception("Certificate not Found! Error: " + ex.Message);

X509CertificateCollection col2 = (X509CertificateCollection)store.FindCertificateBySubjectString(_javaSSLCertName);
Microsoft.Web.Services2.Security.X509.X509Certificate certSSL = null;
    // This sample obtains the first matching certificate from  the collection.
    certSSL = col2[0];
catch (Exception ex)
    thrownew Exception("Certificate not Found! Error: " + ex.Message);

// Instantiate web service proxy
javaService = new javaServiceWS_vs0();
// Add the client certificate to the web service proxy

// Create a security token to sign SOAP messages
X509SecurityToken securityToken = new X509SecurityToken(cert);

// Get the Soap context from the web service proxy class
SoapContext requestContext = javaService.RequestSoapContext;
// Adds the security token
// Specifies the security token to sign the message with
requestContext.Security.Elements.Add(new MessageSignature(securityToken));
requestContext.Security.EncodedMustUnderstand = "0";

// Specify the url that the web service proxy should use, overrides web.config value
javaService.Url = _javaWebServiceURL;
javaService.Timeout = 60000;

var result = javaService.DummyCall("123");

Any help would be appreciated

I recently had trouble accessing the web services on a newly configured machine.  I found that IIS did not have a handler mapping for *.svc files.  This can happen when IIS is installed late (after installing .Net or WCF).  This article describes how to fix it: http://msdn.microsoft.com/en-us/library/ms752252.aspx


our enviornment is setup as follows:

OS: Win 2008 R2

Tools: VS 2010, Sharepoint Designer 2010, SQL SERVER 2008

1) I developed a custome Web Part in VS 2010 with html table in a usercontrol.ascx, I then deployed this UserControl.ascx to the server.

 2) in the share point designer I created the SOAP Service Connection. by going to, Data Sources > SOAP Service Connection enter the URL for the Web Service to create the service.

3) I then created a aspx page, and added a web part zone and in it I have added the custom web part I created.

4) I can see the Web Service in the "Data Source Details" pane in the sharepoint 2010 designer

What we want to achive is to be able to do is without writing code connect the web service to the custom web part.

I am unable to get the data from the web service into the custom web part I have added.

any help in this matter will be greatly appreciated.

and many thanks in advance.

Kind Regards :)


Hi All,

          I want to consume a web service in windows service but in windows service I am not able to access  web service. I have tried it in windows application and web application it is working fine but in windows service  it is not accessible.


i am getting error:-   at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
   at System.Net.Sockets.Socket.InternalConnect(EndPoint remoteEP)
   at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)--->   at System.Net.HttpWebRequest.GetRequestStream()
   at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
   at Testmachone.MachWebRef.SimCardWS.ProvisionImsiCard(String MsMin, String MsEsn, String CardId, String UserId, String Password, String MscId, String BId, String NewValue, ActionTypes Command, String MDN, String COS, String MIP_KEY, String MEID, String RADIUSPassword, String IMSI, Boolean PrePaid)

 any body can help me what could be issue





I'm working on an app which makes multiple SSL requests to a web service. The service has the certificate, there are no client certificates in use. If I look at the messages in Fiddler, it looks like there is an HTTP CONNECT for every request, which gets the servers public key and then makes the actual SSL request. 

Do I need to do something in the client proxy code to cache the servers certificate to avoid the HTTP CONNECT call every time?

Thanks, casey


Hi Guys

I have been struggling for days trying to consume a Java web service which uses X509 certificates over HTTPS. The web service is hosted by a 3rd party, and I have been testing this using SoapUI so I know what the requests and responses should look like.

After much heartache, I now have this working in WCF as well, but it is now validating correctly.

The error that I am receiving in my code is as follows:

System.ServiceModel.Security.MessageSecurityException: Message security verification failed. ---&amp; gt; System.Xml.XmlException: Cannot read KeyIdentifierClause from element 'X509IssuerSerial' with namespace 'http://www.w3.org/2000/09/xmldsig#'.  Custom KeyIdentifierClauses require custom SecurityTokenSerializers, please refer to the SDK for examples.

I believe that the error is being caused by the following element in the response. We are not using Custom Key Identifiers, only the X509 security tokens as required in the specification. The error may be referring to the following part of the response header.

<ds:KeyInfoId="KeyId-73138792 ">

  <wsse:SecurityTokenReferencewsu:Id="STRId-883031060 "xmlns:wsu= "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd ">


      <ds:X509IssuerName>CN=My Root CA,OU=IT Section,O=My Company,C=QA</ds:X509IssuerName>





According to the XSD from http://www.w3.org/2000/09/xmldsig# , the element X509IssuerSerial should be the child of X509Data element. This may or may not be the problem.

I have used Fiddler and can see the request and I can see the correct response being sent back, and this is the same response that I receive back in SoapUI. However the above error is causing me to not be able to get at the resopnse in code. What am I missing?

The binding settings that I got to work are:

          <binding name="Qtel.Gateway__1.0">
              <security authenticationMode="CertificateOverTransport" requireDerivedKeys="false"
                  <localClientSettings timestampValidityDuration="00:10:00" />
                  <secureConversationBootstrap />
              <textMessageEncoding messageVersion="Soap11WSAddressing10" />
              <httpsTransport requireClientCertificate="true" />
  </bindings>  <client>
      <endpoint address="" binding="customBinding"
          bindingConfiguration="Qtel.Gateway__1.0" contract="QtelB2bService.QtelGateway"
          name="Qtel.Gateway__1.0_HTTPSPort" behaviorConfiguration="ClientCertificateBehavior">
            <dns value="b2b-ext.qtel.com.qa" />

      <endpoint address="https://www.test.com/SOAP" binding="customBinding"
          bindingConfiguration="TEST.Gateway__1.0" contract="TESTB2bService.QtelGateway"
          name="TEST.Gateway__1.0_HTTPSPort" behaviorConfiguration="ClientCertificateBehavior">
            <dns value="www.test.com" />

          <behavior name="ClientCertificateBehavior">
                  <clientCertificate findValue="priocept.com" storeLocation="CurrentUser"
                      storeName="Root" x509FindType="FindBySubjectName" />
                      <authentication certificateValidationMode="None" />

I have trace logging turned on, please let me know if you need more info and I will post this up.


Many thanks


I am trying to use the CRM Discovery and CRM Services via Java after having created the stub client classes from the wsdl files. In C# you can use the CrmSdk to get a handle to the LogonManager to get a passportTicket for authentication when using these web services. In Java however, this functionality appears to be missing.

How can I get authenticated in order to use these web services in Java?

The MS sample code for C# is the following:
Code Snippet
// Create and configure the CrmDiscoveryService Web service.
CrmDiscoveryService discoveryService = new CrmDiscoveryService();
discoveryService.Url =

// Retrieve a policy from the Web service.
RetrievePolicyRequest policyRequest = new RetrievePolicyRequest();
RetrievePolicyResponse policyResponse =

// Retrieve a ticket from the Windows Live (Passport) service.
LogonManager lm = new LogonManager();
string passportTicket = lm.Logon(_username, _password, _partner,
    policyResponse.Policy, _environment);
// Dispose of the LogonManager object to avoid a FileNotOpen exception.

// Retrieve a list of organizations that the logged on user is a member of.
RetrieveOrganizationsRequest orgRequest = new RetrieveOrganizationsRequest();
orgRequest.PassportTicket = passportTicket;
RetrieveOrganizationsResponse orgResponse =

// Locate the target organization.
OrganizationDetail orgInfo = null;
foreach (OrganizationDetail orgDetail in orgResponse.OrganizationDetails)
    if (orgDetail.OrganizationName.Equals("AdventureWorksCycle"))
        orgInfo = orgDetail;

if (orgInfo == null)
    throw new Exception("The specified organization was not found.");

// Retrieve a CrmTicket from the Web service.
RetrieveCrmTicketRequest crmTicketRequest = new RetrieveCrmTicketRequest();
crmTicketRequest.OrganizationName = orgInfo.OrganizationName;
crmTicketRequest.PassportTicket = passportTicket;

RetrieveCrmTicketResponse crmTicketResponse =

Hi everyone, I am having .net client consuming axis2 webservice developed in Java. I am using certificates to sign the request and unsigning the response with WCF support. Service providers are signing the responses. I was able to unsign the successful responses from service and displaying on the page,but when the service is sending the faultexception i am getting this error "an unsecured or incorrectly secured fault was recieved from other end" Please find below the complete error System.ServiceModel.Security.MessageSecurityException: An unsecured or incorrectly secured fault was received from the other party. See the inner FaultException for the fault code and detail. ---> System.ServiceModel.FaultException: Error while executing StatementInformation --- End of inner exception stack trace --- Server stack trace: at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.ProcessReply(Message reply, SecurityProtocolCorrelationState correlationState, TimeSpan timeout) at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.Request(Message message, TimeSpan timeout) at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout) at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout) at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs) at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation) at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message) Exception rethrown at [0]: at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) at SampleTester.ServiceReference2.StatementService.StatementInformation(StatementInformationRequest request) at SampleTester.ServiceReference2.StatementServiceClient.ServiceReference2_StatementService_StatementInformation(StatementInformationRequest request) in D:\with new SM(Req signing)\SampleTester\SampleTester\Service References\ServiceReference2\Reference.vb:line 1054 at SampleTester.SATester.btnInvoke_ServerClick(Object sender, EventArgs e) in D:\with new SM(Req signing)\SampleTester\SampleTester\SampleTester.aspx.vb:line 172

I'm trying to expose a simple REST web HTTP service to a Java and Ruby client, in a similar fashion like a WCF Data Service. I use two classes for this purpose:


1. SampleItem:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;

namespace WcfRestService2
 // TODO: Edit the SampleItem classpublicclass SampleItem
  publicint Id { get; set; }
  publicstring StringValue { get; set; }

2. Service1:

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;

namespace WcfRestService2
 // Start the service and browse to http://<machine_name>:<port>/Service1/help to view the service's generated help page// NOTE: By default, a new instance of the service is created for each call; change the InstanceContextMode to Single if you want// a single instance of the service to process all calls.	
 [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
 [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
 // NOTE: If the service is renamed, remember to update the global.asax.cs filepublicclass Service1
  // TODO: Implement the collection resource that will contain the SampleItem instances

  [WebGet(UriTemplate = "")]
  public List<SampleItem> GetCollection()

   // TODO: Replace the current implementation to return a collection of SampleItem instancesreturnnew List<SampleItem>() { new SampleItem() { Id = 1, StringValue = "HELLO WORLD"} };

  [WebInvoke(UriTemplate = "", Method = "POST")]
  public SampleItem Create(SampleItem instance)
   // TODO: Add the new instance of SampleItem to the collectionthrownew NotImplementedException();

  [WebGet(UriTemplate = "{id}")]
  public SampleItem Get(string id)
   // TODO: Return the instance of SampleItem with the given idthrownew NotImplementedException();

  [WebInvoke(UriTemplate = "{id}", Method = "PUT")]
  public SampleItem Update(string id, SampleItem instance)
   // TODO: Update the given instance of SampleItem in the collectionthrownew NotImplementedException();

  [WebInvoke(UriTemplate = "{id}", Method = "DELETE")]
  publicvoid Delete(string id)
   // TODO: Remove the instance of SampleItem with the given id from the collectionthrownew NotImplementedException();


The web.config file looks like this:

<?xmlversion="1.0"?><configuration><system.web><compilationdebug="true"targetFramework="4.0"/><hostingEnvironmentshadowCopyBinAssemblies="false"/></system.web><system.webServer><modulesrunAllManagedModulesForAllRequests="true"><addname="UrlRoutingModule"type="System.Web.Routing.UrlRoutingModule, System.Web, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/></modules></system.webServer><system.serviceModel><behaviors><serviceBehaviors><behaviorname="SimpleServiceBehavior"><serviceMetadatahttpGetEnabled="True"policyVersion="Policy12"/></behavior></serviceBehaviors></behaviors><serviceHostingEnvironmentaspNetCompatibilityEnabled="true"/><standardEndpoints><webHttpEndpoint><!-- 
   Configure the WCF REST service base address via the global.asax.cs file and the default endpoint 
   via the attributes on the <standardEndpoint> element below
  --><standardEndpointname="" helpEnabled="true"automaticFormatSelectionEnabled="true"/></webHttpEndpoint></standardEndpoints></system.serviceModel></configuration>

However, when I try to access the service with e.g Java RESTLET, I get the following error: 


Can't get the metadata for http://localhost:62965/Service1/ (response's status: Bad Request (400) - Bad Request)


which worked fine with my WCF Data Service (the metadata was exposed in a fashion like: localhost:port/ServiceName/$metadata).


How can I enable the metadata for my REST web HTTP service, so other clients can interpret the service?


I am trying to use WCF to call a Java Web Service.  The Web Service has several security requirements based on the Basic Security Profile 1.0:
- The client and service should both use certificates
  - The certificates will be used to sign and encrypt the message.
- In addition, a supporting UsernameToken should be included.

Based on those requirements, it seems like I should be using the MutualCertificate (or MutualCertificateDuplex) authentication mode:
textMessageEncodingmessageVersion="Soap11" />

And then I need to add a supporting token for the user name.  Something like:
BindingElementCollection elements = binding.CreateBindingElements();
SecurityBindingElement security = elements.Find<SecurityBindingElement>();
UserNameSecurityTokenParameters tokenParameters = newUserNameSecurityTokenParameters();
tokenParameters.InclusionMode =
tokenParameters.RequireDerivedKeys =

Once I setup all of the credentials (client certificate, default service certificate, and ClientCredentials.UserName on the client proxy) I can send an acceptable message to the Web Service.
  - It can decrypt the UsernameToken and Body elements
  - It can validate the Signature
  - It generates an encrypted and signed response back to me.

This is where the problem starts.  WCF cannot process the response coming back. 
There are two X509 Tokens used in the response:
1. One token for encrypting the message (which corresponds to the client's certificate)
2. One token for signing the message (which corresponds to the service's certificate)

Both of these X509 tokens are included in the response as <BinarySecurityToken>'s.  The <SecurityTokenReference> elements in the signature and encryption reference the appropriate BinarySecurityToken (Internal references).

My client throws one of two exceptions.  Either:
> "Cannot find a token authenticator for the 'System.IdentityModel.Tokens.X509SecurityToken' token type. Tokens of that type cannot be accepted according to current security settings."
or (if allowSerializedSigningTokenOnReply="true", and depending on the order of the security headers) :
> "The incoming message was signed with a token which was different from what used to encrypt the body. This was not expected."

I can create a Mock Web Service using WCF that corresponds to these security requirements, and my client is able to process the response from it.  The only differences I can see are:
  - There are no <BinarySecurityToken> elements by default and the <SecurityTokenReference> elements include <X509Data> elements instead (External references).
  - If I change the authenticationMode for my Mock web service to MutualCertificateDuplex, then it will include the signature X509 Token as a BinarySecurityToken (Internal reference) but the encryption X509 Security Token is still an external reference.
     * In this case, allowSerializedSigningTokenOnReply="true" must be set on the client in order to process it or I'll get the same "Cannot find a token authenticator..." error as above.

So I know how WCF expects it to look, and it isn't very different -- it simply expects one or both X509 Tokens to use External references instead of Internal references.  It's so close.  (And I asked if the Java Web Service could be changed to use External references, but it didn't seem possible with the third party tools being used.)

But I can't find any way to make WCF read both BinarySecurityTokens.  Setting allowSerializedSigningTokenOnReply allows it to read one BinarySecurityToken, but even that appears to make assumptions about what the BinarySecurityToken will be -- the error says that the problem is that the message was signed with a token which was different from the token used for encryption, but that works just fine in my Mock Web Service that uses external references for the X509 tokens.  So the problem must be that it gets confused if there is more than one BinarySecurityToken, or the token is for encryption instead of signing.

So the question is -- is it possible to support this type of Interop using WCF?
- I've looked at using custom credentials, custom behaviors, custom bindings, etc, but none of those seem to have any impact on how the AsymmetricSecurityBindingElement processes the BinarySecurityTokens.
- I've looked at the code in Reflector, but I can't see anything I can do that would affect the client's handling of the response, without also changing the request it sends to the service.
- I've even considered cloning the entire AsymmetricSecurityBindingElement, but there are so many internal methods and sealed classes that it seemed like I would end up replicating 90% of WCF in the process, if it were even possible.

And if it is not possible to do this using WCF, what alternatives do I have (instead of WCF, or to propose as an equivalent security policy that is more likely to interoperate between WCF and a different implementation)?

With the release of the Silverlight control the web services have also been updated. As such it may be necessary to regenerate your proxy files.

Hi everybody,

I'm implementing a WCF client which talks to a Java web service secured with x509 certificates and username token. The service requires both signing and encryption as message protection.

Thanks to Yaron Naveh and some other guys on this forum I've managed to solve the signing stuff, but the encryption seems to be much more difficult.

The problem I'm facing now is the server cannot decrypt my messages - I'm getting HTTP 500 errors. I've got a request example from the service vendor and compared with the messages my client generates, there is only one difference: in the example provided by service vendor I can see an extra tag KeyInfo under the EncryptedData, which seems to me reasonable to be there, but I don't know why WCF doesn't put that item. These are the two SOAP request sections I'm talking about:

My WCF client:

<:Bodyu:Id="_1"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:xsd="http://www.w3.org/2001/XMLSchema"><e:EncryptedDataId="_2"Type="http://www.w3.org/2001/04/xmlenc#Content"xmlns:e="http://www.w3.org/2001/04/xmlenc#"><e:EncryptionMethodAlgorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc"/><e:CipherData><e:CipherValue><!-- Removed--></e:CipherValue></e:CipherData></e:EncryptedData></:Body>

Vendor example:

<soapenv:Bodywsu:Id="id-14"xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"><xenc:EncryptedDataId="EncDataId-15"Type="http://www.w3.org/2001/04/xmlenc#Content"><xenc:EncryptionMethodAlgorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc"/><ds:KeyInfoxmlns:ds="http://www.w3.org/2000/09/xmldsig#"><wsse:SecurityTokenReferencexmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"><wsse:ReferenceURI="#EncKeyId-3817A46FC5FA496318127532057644218"/></wsse:SecurityTokenReference></ds:KeyInfo><xenc:CipherData><xenc:CipherValue><!-- Removed --></xenc:CipherValue></xenc:CipherData></xenc:EncryptedData></soapenv:Body>

My client is configured as follows:


Does anybody know how should I force WCF to add the KeyInfo item in EncryptedData. As this is the only difference it's the only thing I can think to be wrong in my client.

Does anybody think about any interoperability issues which would block me from correctly encrypt messages?

Any help is more than welcomed.


Many thanks,

Mihai Maier


I’m writing a WCF client that consumes a third party Java web service. The web service has some of its methods overloaded:

wsdl:operationname="search"parameterOrder="houseNameNumber postCode">
wsdl:operationname="search"parameterOrder="langaugeCode houseNameNumber postCode">
wsdl:operationname="search"parameterOrder="addressLine1 addressLine2 addressLine3 postTown postCode">

When I generate the client’s proxy, the overloaded methods are suffixed with a number (search, seach1, search2,…) If I try to run the client and call for example the search2 method, I get an exception “Invalid method ‘search2’”. This makes sense because there isn’t any ‘search2’ method exposed by the web service.

Is there a way how to modify the WCF client’s references file to support overloaded methods from the Java web service? I noticed that simply renaming the methods won’t help and throws an exception at runtime when I try to open the proxy.



I've problem using Java web method (Servlet/2.5 JSP/2.1) using WCF. Messages are signed (not encrypted) and secured via SSL. Calls and results seem to be OK, but .NET framework thows MessageSecurityException  "Message security verification failed" (Inner exception is "Supporting token signatures not expected").

It seems to me, the web service call returns some result (see <ns1:aviso xmlns:ns1="http://www.gem.com/b2b"></ns1:aviso> result), but the message canot be 'deserialized' by .NET Framework (.NET 4.0 Client Profile).

Does anybody know how to solve this issue?

Thans a lot!

Program.cs (app. config is empty)

staticvoid Main(string[] args)


   BasicHttpBinding binding = new BasicHttpBinding();

   EndpointAddress endpoint = new EndpointAddress("https://simu.b2b.vzp.cz/B2BProxy/HttpProxy/SIMUWSSZiskejAvizo");

   processRequest request = new processRequest();

   binding.Security.Mode = BasicHttpSecurityMode.TransportWithMessageCredential;

   binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;

   binding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.Certificate;

   ZiskejAvizoPortTypeClient service = new ZiskejAvizoPortTypeClient(binding, endpoint);

   service.ClientCredentials.ClientCertificate.Certificate = new X509Certificate2(@"D:\data\cert\CustomCert.pfx", "password");



    processResponse response = ((ZiskejAvizoPortType)service).process(request);

    // Process response...


   catch (Exception ex)





SOAP Request:


Soap Response (HTTP Status 200 - OK)





  </ds:SignatureValue><ds:KeyInfoId="KeyId-13669278"><wsse:SecurityTokenReferencexmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"wsu:Id="STRId-25918445"><ds:X509Data><ds:X509IssuerSerial><ds:X509IssuerName>CN=VZP CR Subordinate CA,OU=CA-W3K,O=VZP,C=CZ,EMAILADDRESS=subCA@vzp.cz</ds:X509IssuerName><ds:X509SerialNumber>120205296742123446608706</ds:X509SerialNumber></ds:X509IssuerSerial></ds:X509Data></wsse:SecurityTokenReference></ds:KeyInfo></ds:Signature></wsse:Security></soapenv:Header><soapenv:Bodyxmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"wsu:Id="Id-31794935"><ns1:avisoxmlns:ns1="http://www.gem.com/b2b"></ns1:aviso></soapenv:Body></soapenv:Envelope>


I have a .net client that consumes an operation on a java based web service that appears to work accept for an issue with passing Boolean values back to the service in the soap message. Any member of the complex type that are defined as Boolean in the service contract will not be present in the soap message generated from the client even though they are set in the code.

Sample Client Code:




proxy = newUpdateChecklistItemStatusPortTypeClient();



updateChecklistItemStatusReq request = newupdateChecklistItemStatusReq();

request.ouid =



request.applicationId =



request.adminFunction =



request.checklistItemTypeCode =



request.ceebCode =



request.transcriptTerm =



request.transcriptScores =





updateChecklistItemStatusRsp response = newupdateChecklistItemStatusRsp();

response = proxy.UpdateChecklistItemStatusOp(request);

Client Soap Message Generated:

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">

  <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

    <updateChecklistItemStatusReq xmlns="http://www.ohio.edu/schema/checklistservice">

      <ouid xmlns="">P001222931</ouid>

      <applicationId xmlns="">00000032</applicationId>

      <adminFunction xmlns="">ADMA</adminFunction>

      <checklistItemTypeCode xmlns="">UHSTRN</checklistItemTypeCode>

      <ceebCode xmlns="">052046</ceebCode>

      <transcriptTerm xmlns="">FINAL</transcriptTerm>




As you can see the transcriptScores element is not present.

snippet of wsdl that contains the transcriptScores definition:

<element maxOccurs="1" minOccurs="0" name="transcriptScores" type="boolean">
       <documentation>This flag indicates whether or not a high school transcript has ACT or
              SAT scores reported on it.  If not set, it is assumed to be false.
              If set to true, then would satisfy the UACTSA checklist item.</documentation>

Any suggestions on why this is occurring?



<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure