none
Como puedo resolver el error ID3242: The security token could not be authenticated or authorized RRS feed

  • Pregunta

  • Al consumir el Web Service de Dynamics CRM 2011 desde Java me envía el siguiente error, lo curioso es que la semana pasada estuve trabajando con este mismo programa y no enviaba este mensaje, alguien tiene idea por donde lo puedo resolver.

    org.apache.axis2.AxisFault: ID3242: The security token could not be authenticated or authorized.
            at org.apache.axis2.util.Utils.getInboundFaultFromMessageContext(Utils.java:446)
            at org.apache.axis2.description.OutInAxisOperationClient.handleResponse(OutInAxisOperation.java:371)
            at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:417)
            at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:229)
            at org.apache.axis2.client.OperationClient.execute(OperationClient.java:165)
            at java2crmonline.OrganizationServiceStub.retrieveMultiple(OrganizationServiceStub.java:836)
            at java2crmonline.Main.readContacto(Main.java:673)
            at java2crmonline.EmuladorActualizacion.run(EmuladorActualizacion.java:24)
            at java.lang.Thread.run(Thread.java:619)

    Gracias

    martes, 19 de junio de 2012 15:06

Todas las respuestas

  • Hola epinedor,

    Como te estas autenticando?... debes de asegurarte que el usuario este dentro del CRM.

    OFF TOPIC : Cuando me ha tocado hacer algo así, lo que nosotros hemos hecho es un WS en NET y que este sea consumido por el portal en Java. 


    Salu2 Atilin | http://atiliorosas.blogspot.com.es/

    martes, 19 de junio de 2012 15:25
  • Hola Atilio,

    Utilizo una clase que te autentifica, lo peor es que me devuelve los valores de autentificacion.

    organizationServiceURL = "https://miorganizacion.crm.dynamics.com/XrmServices/2011/Organization.svc";       

    liveIDManager = new LiveIDManager();

    securityData = liveIDManager.authenticateWithLiveID(organizationServiceURL, liveIDUseranme, liveIDPassword);

    Key Identifier  : 2WvFAm9+gsfrFUlTu8g59X5OKZE=
    Security Token 1: D9Lyqsf3o5uoZTkSzDVPS5kVPuKm6GEFjve42pxIxFX3MVOdDPG+wutAHPKqtUdD0wlNyznmNc9L8RyMwhjqszAydeLLydh4JSJEleqWUZ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FvGb6wl0ZFXJ54D6ioH3FOIFhQ==

    Pero como lo comentaba la semana pasada esto mismo si funcionaba.

    Gracias.


    Edgar Pinedo

    martes, 19 de junio de 2012 15:35
  • Hola Edgar

    nos puedes mostrar como lo haces en authenticateWithLiveID? Verifica primero si te conectar al servicio (https://miorganizacion.crm.dynamics.com/XrmServices/2011/Organization.svc) , luego con el mismo usuario con el que autentica el servicio entra al CRM y dinos si hay error. 

    Este es codigo del CRM 4 pero creo que no cambia mucho

    
    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;  
    
    private static String domain = "DOMAIN";   
    
    private static String orgName = "THIS_IS_REQUIRED"; 
    
    
    public static void main(String[] args) {  
    
        CrmServiceStub stub;  
        try {  
            stub = new CrmServiceStub(endpointURL);  
            setOptions(stub._getServiceClient().getOptions());  
    
            RetrieveMultipleDocument rmd = RetrieveMultipleDocument.Factory.newInstance();  
            RetrieveMultiple rm = RetrieveMultiple.Factory.newInstance();  
    
            QueryExpression query = QueryExpression.Factory.newInstance();  
            query.setColumnSet(AllColumns.Factory.newInstance());  
            query.setEntityName(EntityName.######.toString());  
    
    
            rm.setQuery(query);  
            rmd.setRetrieveMultiple(rm);  
    
            CrmAuthenticationTokenDocument catd = CrmAuthenticationTokenDocument.Factory.newInstance();  
            CrmAuthenticationToken token = CrmAuthenticationToken.Factory.newInstance();  
            token.setAuthenticationType(0);     
            token.setOrganizationName(orgName);  
            catd.setCrmAuthenticationToken(token);  
    
            boolean fetchNext = true;  
            while(fetchNext){  
                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++){  
    
                    ### myEntity = (###) myEntitiesAtLast[i];  
                }  
            }  
        }   
        catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
    
    private static void setOptions(Options options){  
        HttpTransportProperties.Authenticator auth = new HttpTransportProperties.Authenticator();  
    
        List authSchemes = new ArrayList();  
        authSchemes.add(HttpTransportProperties.Authenticator.NTLM);   
        auth.setAuthSchemes(authSchemes);   
    
        auth.setUsername(userName);  
        auth.setPassword(password);  
        auth.setHost(host);  
        auth.setPort(port);  
        auth.setDomain(domain);  
        auth.setPreemptiveAuthentication(false); 
        options.setProperty(HTTPConstants.AUTHENTICATE, auth);  
        options.setProperty(HTTPConstants.REUSE_HTTP_CLIENT, "true");
    }

     


    Salu2 Atilin | http://atiliorosas.blogspot.com.es/

    • Propuesto como respuesta Atilio martes, 19 de junio de 2012 15:46
    martes, 19 de junio de 2012 15:46
  • Y como creo que tu CRM es online, te dejo aca un link interesante

    http://zsvoboda.blogspot.com.es/2011/03/connecting-to-microsoft-crm-2011-online.html



    Salu2 Atilin | http://atiliorosas.blogspot.com.es/

    • Propuesto como respuesta Atilio martes, 19 de junio de 2012 15:47
    martes, 19 de junio de 2012 15:47
  • Este es el codigo de LiveIDManager

    package java2crmonline;

    import java.io.ByteArrayInputStream;
    import java.io.IOException;
    import java.text.SimpleDateFormat;
    import java.util.*;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.params.BasicHttpParams;
    import org.apache.http.params.CoreConnectionPNames;
    import org.apache.http.params.HttpParams;
    import org.apache.http.util.EntityUtils;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.xpath.XPath;
    import javax.xml.xpath.XPathConstants;
    import javax.xml.xpath.XPathExpressionException;
    import javax.xml.xpath.XPathFactory;
    import org.w3c.dom.Document;
    import org.w3c.dom.Node;
    import org.xml.sax.SAXException;
    import org.apache.log4j.Logger;

    public class LiveIDManager {
        static Logger logger = Logger.getLogger(Main.class.getName());

        public SecurityData authenticateWithLiveID(String CRMUrl, String liveIDUsername, String liveIDPassword) {
            // Generates random credentials (Username, Password & Application ID) for the device
            // Sends the credentials to WLID and gets a PUID back
            DeviceCredentials deviceCredentials = DeviceIdManager.RegisterDevice();

            // Register Device Credentials and get binaryDAToken
            String deviceCredentialsSoapTemplate = "<s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\""
                    + " xmlns:a=\"http://www.w3.org/2005/08/addressing\""
                    + " xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">"
                    + "<s:Header>"
                    + "    <a:Action s:mustUnderstand=\"1\">"
                    + "    http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue</a:Action>"
                    + "    <a:MessageID>urn:uuid:%s</a:MessageID>"
                    + "    <a:ReplyTo>"
                    + "        <a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>"
                    + "    </a:ReplyTo>"
                    + "    <a:To s:mustUnderstand=\"1\">"
                    + "    https://login.live.com/liveidSTS.srf</a:To>"
                    + "    <o:Security s:mustUnderstand=\"1\""
                    + "    xmlns:o=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\">"
                    + "        <u:Timestamp u:Id=\"_0\">"
                    + "        <u:Created>%sZ</u:Created>"
                    + "        <u:Expires>%sZ</u:Expires>"
                    + "        </u:Timestamp>"
                    + "        <o:UsernameToken u:Id=\"devicesoftware\">"
                    + "        <o:Username>%s</o:Username>"
                    + "        <o:Password Type=\"%s</o:Password">http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">%s</o:Password>"
                    + "        </o:UsernameToken>"
                    + "    </o:Security>"
                    + "    </s:Header>"
                    + "   <s:Body>"
                    + "   <t:RequestSecurityToken xmlns:t=\"http://schemas.xmlsoap.org/ws/2005/02/trust\">"
                    + "        <wsp:AppliesTo xmlns:wsp=\"http://schemas.xmlsoap.org/ws/2004/09/policy\">"
                    + "        <a:EndpointReference>"
                    + "            <a:Address>http://passport.net/tb</a:Address>"
                    + "        </a:EndpointReference>"
                    + "        </wsp:AppliesTo>"
                    + "        <t:RequestType>"
                    + "        http://schemas.xmlsoap.org/ws/2005/02/trust/Issue</t:RequestType>"
                    + "    </t:RequestSecurityToken>"
                    + "    </s:Body>"
                    + "</s:Envelope>";

            RequestDateTimeData requestDateTime = getRequestDateTime();

            String soapTemplate = String.format(
                    deviceCredentialsSoapTemplate,
                    UUID.randomUUID().toString(),
                    requestDateTime.getCreatedDateTime(),
                    requestDateTime.getExpiresDateTime(),
                    "11" + deviceCredentials.getDeviceName(),
                    deviceCredentials.getPassword());

            logger.debug("Device Credential Request: " + soapTemplate);

            String binaryDATokenXML = GetSOAPResponse(
                    "https://login.live.com/liveidSTS.srf",
                    soapTemplate);

            System.out.println("ciper: " + binaryDATokenXML);

            logger.debug("Live ID Response: " + binaryDATokenXML);

            String cipherValue = GetValueFromXML(binaryDATokenXML, "//*[local-name()='CipherValue']");

            logger.debug("CipherValue: " + cipherValue);

            // Step 3: Get Security Token by sending WLID username, password and device binaryDAToken
            String securityTokenSoapTemplate = "<s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\""
                    + " xmlns:a=\"http://www.w3.org/2005/08/addressing\""
                    + " xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">"
                    + "<s:Header>"
                    + "    <a:Action s:mustUnderstand=\"1\">"
                    + "    http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue</a:Action>"
                    + "    <a:MessageID>urn:uuid:%s</a:MessageID>"
                    + "    <a:ReplyTo>"
                    + "      <a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>"
                    + "    </a:ReplyTo>"
                    + "    <VsDebuggerCausalityData xmlns=\"http://schemas.microsoft.com/vstudio/diagnostics/servicemodelsink\">"
                    + "    uIDPozBEz+P/wJdOhoN2XNauvYcAAAAAK0Y6fOjvMEqbgs9ivCmFPaZlxcAnCJ1GiX+Rpi09nSYACQAA</VsDebuggerCausalityData>"
                    + "    <a:To s:mustUnderstand=\"1\">"
                    + "    https://login.live.com/liveidSTS.srf</a:To>"
                    + "    <o:Security s:mustUnderstand=\"1\""
                    + "    xmlns:o=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\">"
                    + "      <u:Timestamp u:Id=\"_0\">"
                    + "       <u:Created>%sZ</u:Created>"
                    + "       <u:Expires>%sZ</u:Expires>"
                    + "      </u:Timestamp>"
                    + "      <o:UsernameToken u:Id=\"user\">"
                    + "        <o:Username>%s</o:Username>"
                    + "        <o:Password Type=\"%s</o:Password">http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">%s</o:Password>"
                    + "      </o:UsernameToken>"
                    + "      <wsse:BinarySecurityToken ValueType=\"urn:liveid:device\""
                    + "      xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\">"
                    + "        <EncryptedData Id=\"BinaryDAToken0\""
                    + "        Type=\"http://www.w3.org/2001/04/xmlenc#Element\""
                    + "        xmlns=\"http://www.w3.org/2001/04/xmlenc#\">"
                    + "          <EncryptionMethod Algorithm=\"http://www.w3.org/2001/04/xmlenc#tripledes-cbc\">"
                    + "          </EncryptionMethod>"
                    + "          <ds:KeyInfo xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\">"
                    + "            <ds:KeyName>http://Passport.NET/STS</ds:KeyName>"
                    + "          </ds:KeyInfo>"
                    + "          <CipherData>"
                    + "            <CipherValue>"
                    + "              %s"
                    + "            </CipherValue>"
                    + "          </CipherData>"
                    + "        </EncryptedData>"
                    + "      </wsse:BinarySecurityToken>"
                    + "    </o:Security>"
                    + " </s:Header>"
                    + "  <s:Body>"
                    + "    <t:RequestSecurityToken xmlns:t=\"http://schemas.xmlsoap.org/ws/2005/02/trust\">"
                    + "      <wsp:AppliesTo xmlns:wsp=\"http://schemas.xmlsoap.org/ws/2004/09/policy\">"
                    + "        <a:EndpointReference>"
                    + "          <a:Address>%s</a:Address>"
                    + "        </a:EndpointReference>"
                    + "      </wsp:AppliesTo>"
                    + "     <wsp:PolicyReference URI=\"MBI_FED_SSL\""
                    + "      xmlns:wsp=\"http://schemas.xmlsoap.org/ws/2004/09/policy\" />"
                    + "      <t:RequestType>http://schemas.xmlsoap.org/ws/2005/02/trust/Issue</t:RequestType>"
                    + "    </t:RequestSecurityToken>"
                    + "  </s:Body>"
                    + " </s:Envelope>";

            requestDateTime = getRequestDateTime();

            // Create the URN address of the format urn:crm:dynamics.com.
      // Replace crm with crm4 for Europe & crm5 for Asia.
            String URNAddress = "urn:crm:dynamics.com";

            if (CRMUrl.indexOf("crm4.dynamics.com") != -1) {
                URNAddress = "urn:crm4:dynamics.com";
            }

            if (CRMUrl.indexOf("crm5.dynamics.com") != -1) {
                URNAddress = "urn:crm5:dynamics.com";
            }

            String securityTemplate = String.format(
                    securityTokenSoapTemplate,
                    UUID.randomUUID().toString(),
                    requestDateTime.getCreatedDateTime(),
                    requestDateTime.getExpiresDateTime(),
                    liveIDUsername,
                    liveIDPassword,
                    cipherValue,
                    URNAddress);

            logger.debug("Security Token Request: " + securityTemplate);

            String securityTokenXML = GetSOAPResponse(
                    "https://login.live.com/liveidSTS.srf",
                    securityTemplate);

            System.out.println("token xml online : "+securityTokenXML);

            logger.debug("Security Token Response: " + securityTokenXML);

            String securityToken0 = GetValueFromXML(securityTokenXML, "//*[local-name()='CipherValue']");
            String securityToken1 = GetValueFromXML(securityTokenXML, "(//*[local-name()='CipherValue'])[2]");
            String keyIdentifier = GetValueFromXML(securityTokenXML, "//*[local-name()='KeyIdentifier']");

            logger.debug("Security Token 0: " + securityToken0);
            logger.debug("Security Token 1: " + securityToken1);
            logger.debug("Key Identifier: " + keyIdentifier);

            return new SecurityData(keyIdentifier, securityToken0, securityToken1);
        }

        public static RequestDateTimeData getRequestDateTime() {
            TimeZone gmt = TimeZone.getTimeZone("GMT");
            Calendar calendar = Calendar.getInstance(gmt);
            Calendar calendarFiveMinute = (Calendar) calendar.clone();

            calendarFiveMinute.add(Calendar.MINUTE, 5);

            Date binaryDARequestCreatedTime = calendar.getTime();
            Date fiveMinuteFromNow = calendarFiveMinute.getTime();

            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
            formatter.setTimeZone(gmt);

            return new RequestDateTimeData(formatter.format(binaryDARequestCreatedTime), formatter.format(fiveMinuteFromNow));
        }

        private String GetValueFromXML(String inputXML, String xPathQuery) {
            DocumentBuilder builder;
            try {
                builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();

                Document document = builder.parse(new ByteArrayInputStream(inputXML.getBytes()));

                XPath xpath = XPathFactory.newInstance().newXPath();
                String expression = xPathQuery;
                Node cipherValue = (Node) xpath.evaluate(expression, document, XPathConstants.NODE);

                return cipherValue.getTextContent();
            } catch (XPathExpressionException e) {
                logger.error(e.getMessage());
            } catch (ParserConfigurationException e) {
                logger.error(e.getMessage());
            } catch (SAXException e) {
                logger.error(e.getMessage());
            } catch (IOException e) {
                logger.error(e.getMessage());
            }

            return null;
        }

            private static String GetSOAPResponse(String url, String soapEnvelope) {
            HttpResponse response = null;

            //Create the request that will submit the request to the server
            try {
                HttpParams params = new BasicHttpParams();
                params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 180000);

                HttpClient client = new DefaultHttpClient(params);
                HttpPost post = new HttpPost(url);
                StringEntity entity = new StringEntity(soapEnvelope);

                post.setHeader("Content-Type", "application/soap+xml; charset=UTF-8");
                post.setEntity(entity);

                response = client.execute(post);

                return EntityUtils.toString(response.getEntity());
            } catch (ClientProtocolException e) {
                logger.error(e.getMessage());
            } catch (IOException e) {
                logger.error(e.getMessage());
            }

            return null;
        }
    }


    Edgar Pinedo

    martes, 19 de junio de 2012 16:01
  • Muchas gracias, se ve muy interesante.

    Saludos


    Edgar Pinedo

    martes, 19 de junio de 2012 16:04
  • Hola Atilio, como puedo hacer para conectarme a CRM OnPremise, la forma de autentificar es diferente por que en la online se utiliza una cuenta de Live y en onpremise se utiliza el Active directory.

    Edgar Pinedo

    miércoles, 20 de junio de 2012 4:06
  • Hola Edgar,

    No tengo código en Java, pero, te lo puedo dar en C#

    http://atiliorosas.blogspot.com.es/2012/02/aspx-en-crm-2011.html

    ademas, te voy a dejar un link donde la conexión se hace a CRM 4. Acuérdate que esta conexión esta permitida en CRM 2011

    http://social.microsoft.com/Forums/en-US/crmdevelopment/thread/caf5fa3f-c5f0-43a9-8cfc-4fdb88bb6248/ 

    Y este link donde hay una aplicación en Java que esta super interesante, todo en CRM 4, pero repito, vale en CRM 2011

    http://javamscrm.codeplex.com/

    Cuéntame como va, que esta muuuy interesante esto!!! 


    Salu2 Atilin | http://atiliorosas.blogspot.com.es/

    • Propuesto como respuesta Atilio miércoles, 20 de junio de 2012 8:04
    miércoles, 20 de junio de 2012 8:04
  • org.apache.axis2.AxisFault: Transport error: 401 Error: Unauthorized
            at org.apache.axis2.transport.http.HTTPSender.handleResponse(HTTPSender.java:296)
            at org.apache.axis2.transport.http.HTTPSender.sendViaPost(HTTPSender.java:190)
            at org.apache.axis2.transport.http.HTTPSender.send(HTTPSender.java:75)
            at org.apache.axis2.transport.http.CommonsHTTPTransportSender.writeMessageWithCommons(CommonsHTTPTransportSender.java:364)
            at org.apache.axis2.transport.http.CommonsHTTPTransportSender.invoke(CommonsHTTPTransportSender.java:208)
            at org.apache.axis2.engine.AxisEngine.send(AxisEngine.java:448)
            at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:401)
            at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:228)
            at org.apache.axis2.client.OperationClient.execute(OperationClient.java:163)
            at com.microsoft.schemas.crm._2007.webservices.CrmServiceStub.RetrieveMultiple(Unknown Source)
            at onpremise.TestCRM.main(TestCRM.java:83)

    Hola Atilio, ya lo implemente, mi clase principal la anexo, pero me envía una exception:

    org.apache.axis2.AxisFault: Transport error: 401 Error: Unauthorized
            at org.apache.axis2.transport.http.HTTPSender.handleResponse(HTTPSender.java:296)
            at org.apache.axis2.transport.http.HTTPSender.sendViaPost(HTTPSender.java:190)
            at org.apache.axis2.transport.http.HTTPSender.send(HTTPSender.java:75)
            at org.apache.axis2.transport.http.CommonsHTTPTransportSender.writeMessageWithCommons(CommonsHTTPTransportSender.java:364)
            at org.apache.axis2.transport.http.CommonsHTTPTransportSender.invoke(CommonsHTTPTransportSender.java:208)
            at org.apache.axis2.engine.AxisEngine.send(AxisEngine.java:448)
            at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:401)
            at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:228)
            at org.apache.axis2.client.OperationClient.execute(OperationClient.java:163)
            at com.microsoft.schemas.crm._2007.webservices.CrmServiceStub.RetrieveMultiple(Unknown Source)
            at onpremise.TestCRM.main(TestCRM.java:83)

    Mi codigo.

    public class TestCRM {

    private static String endpointURL = "http://10.40.60.20:5555/MSCrmServices/2007/CrmService.asmx";
    private static String userName = "dominio\\usuario";
    private static String password = "Contrasena01";
    private static String host = "10.40.60.20";
    private static int port = 5555;

    //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 = "crmlaureate";

    private static String orgName = "laureatemexicoycentroamerica"; //this does the work....


    public static void main(String[] args) {

        CrmServiceStub stub;
        try {
            stub = new CrmServiceStub(endpointURL);

            setOptions(stub._getServiceClient().getOptions());

            RetrieveMultipleDocument rmd = RetrieveMultipleDocument.Factory.newInstance();
            RetrieveMultiple rm = RetrieveMultiple.Factory.newInstance();

            QueryExpression query = QueryExpression.Factory.newInstance();
            query.setColumnSet(AllColumns.Factory.newInstance());
            query.setEntityName(EntityName.CONTACT.toString());
            //query.setFilter...

            rm.setQuery(query);
            rmd.setRetrieveMultiple(rm);

            //Now this is required. Without it all i got was 401s errors
            CrmAuthenticationTokenDocument catd = CrmAuthenticationTokenDocument.Factory.newInstance();
            CrmAuthenticationToken token = CrmAuthenticationToken.Factory.newInstance();
            token.setAuthenticationType(0);
            token.setOrganizationName(orgName);
            catd.setCrmAuthenticationToken(token);

            System.out.println(catd.getCrmAuthenticationToken().getOrganizationName());
            System.out.println(catd.getCrmAuthenticationToken().getAuthenticationType());
            System.out.println(catd.getCrmAuthenticationToken().getCallerId());
            System.out.println(catd.getCrmAuthenticationToken().getCrmTicket());
            System.out.println(catd.getCrmAuthenticationToken().isSetCrmTicket());
            System.out.println(catd.getCrmAuthenticationToken().isSetOrganizationName());
            System.out.println(catd.getCrmAuthenticationToken().validate());


            boolean fetchNext = true;
            while(fetchNext){
                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...
                    Contact myEntity = (Contact) myEntitiesAtLast[i];
                    System.out.println("contacto: " + myEntity.getFullname());
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void setOptions(Options options){
        HttpTransportProperties.Authenticator auth = new HttpTransportProperties.Authenticator();

        List authSchemes = new ArrayList();
        authSchemes.add(HttpTransportProperties.Authenticator.NTLM);
        auth.setAuthSchemes(authSchemes);

        auth.setUsername(userName);
        auth.setPassword(password);
        auth.setHost(host);
        auth.setPort(port);
        auth.setDomain(domain);
        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
    }
    }

    Pero no me esta autenticando. Alguna idea??


    Edgar Pinedo

    miércoles, 20 de junio de 2012 23:17
  • Hola Edgar,

    Déjame entrar a mi Eclipse y lo voy a probar si?. 

    Saludos


    Salu2 Atilin | http://atiliorosas.blogspot.com.es/

    jueves, 21 de junio de 2012 7:28
  • Hola Atilio, pudiste probar en Eclipse?

    Para ver la falla.


    Edgar Pinedo

    sábado, 23 de junio de 2012 0:05
  • No, lo siento hoy en la tarde me pongo con esto.

    Saludos y disculpas


    Salu2 Atilin | http://atiliorosas.blogspot.com.es/

    lunes, 25 de junio de 2012 7:43