Autor Tema: Problemas al consumir Web Service  (Leído 5432 veces)

0 Usuarios y 1 Visitante están viendo este tema.

Desconectado NIGHTGHOST

  • Ghost User -
  • -^- Elite Gold -^-
  • The Communiter-
  • **
  • Mensajes: 1997
  • I'm Sparky... I'm NightWolf... User SVC
Problemas al consumir Web Service
« : junio 11, 2013, 12:59:13 pm »
Bueno inicio comentandoles que estoy trabajando en C# .net 2010, con el framework 2.0

Estoy realizando un Web Service Interno que viajará hacia otro Web Service Externo, pero debo enviarle en el Soap header el Username y Password; Y este es el problema que no se como enviarselo.

Para poder consumir el Web Service Externo, he generado un archivo clase(.cs) con la herramienta WSDL.exe desde el MS DOS: "Wsdl.exe http://172.31.11.20:7880/MISERVICIO/MISERVICIO.asmx?WSDL"

Y lo tengo de la siguiente forma:

Código: [Seleccionar]
ESB_PUNTO_UNICO_ACCESO_Service WSMH = new ESB_PUNTO_UNICO_ACCESO_Service();
BPEL_SOA_PUNTO_UNICOProcessRequest Consulta = new BPEL_SOA_PUNTO_UNICOProcessRequest();
BPEL_SOA_PUNTO_UNICOProcessRequestDetalle detalleC = new BPEL_SOA_PUNTO_UNICOProcessRequestDetalle();
BPEL_SOA_PUNTO_UNICOProcessResponse Respuesta = new BPEL_SOA_PUNTO_UNICOProcessResponse();

Consulta.ID_TRANSACCION = "1";
Consulta.TIPO_TRAMA = "XML";
Consulta.Achivo = null;                   
detalleC.atributo = "NIT";
detalleC.valor = pNit;
Consulta.detalle = detalleC;

Respuesta = WSMH.execute(Consulta);

Estuve googleando pero no encuentro la respuesta a mi necesidad, intente aplicarlo de la siguiente forma(antes del execute) pero no tuve suerte

Código: [Seleccionar]
ICredentials credentials = new NetworkCredential("prueba", "mipass");
WSMH.Credentials = credentials;
WSMH.PreAuthenticate = true;

Este es el XML del SOAP de como lo debería de recibir el Web Service Externo
Código: [Seleccionar]
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
    <soap:Header>
        <wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" soap:mustUnderstand="1">
            <wsse:UsernameToken xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
                <wsse:Username>macedonia.unico</wsse:Username>
                <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">punico2013</wsse:Password>
            </wsse:UsernameToken>
        </wsse:Security>
    </soap:Header>
    <soap:Body xmlns:ns1="http://xmlns.oracle.com/BPEL_SOA_PUNTO_UNICO">
        <ns1:BPEL_SOA_PUNTO_UNICOProcessRequest>
            <ns1:ID_TRANSACCION>1</ns1:ID_TRANSACCION>
            <ns1:TIPO_TRAMA>XML</ns1:TIPO_TRAMA>
            <ns1:detalle>
                <ns1:atributo>NIT</ns1:atributo>
                <ns1:valor>06142601831130</ns1:valor>
            </ns1:detalle>
            <ns1:Achivo/>
        </ns1:BPEL_SOA_PUNTO_UNICOProcessRequest>
    </soap:Body>
</soap:Envelope>

¿Alguien me puede orientar?  :sorry:
« Última Modificación: junio 13, 2013, 05:08:46 pm por NIGHTGHOST »


Desconectado NIGHTGHOST

  • Ghost User -
  • -^- Elite Gold -^-
  • The Communiter-
  • **
  • Mensajes: 1997
  • I'm Sparky... I'm NightWolf... User SVC
Re:Problemas al consumir Web Service
« Respuesta #1 : junio 12, 2013, 12:09:53 pm »
¿Nadie?  :cry:

¿Alguien tiene otra alternativa o ejemplo en Java enviando en el soap header el username y password?  :phew:

Cree un proyecto en Netbeans consumendo un WebMethod del Web Service Externo  y disque enviando los parametros al Soap Header pero nel, tampoco me funciona.
Código: [Seleccionar]
package WSPRUEBA;

import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;
//import WSPRUEBA.Detalle;
import PUNTO_UNICO.BPELSOAPUNTOUNICOProcessRequest.Detalle;

/**
 *
 * @author José M. Flores
 */
@WebService(serviceName = "WSPRUEBA")
public class WSPRUEBA {

    @WebMethod(operationName = "Consultar")
    @SuppressWarnings({"null", "ConstantConditions"})
    public String ConsultaNit(@WebParam(name = "Nit") String Nit) {
        String msg = null;
        try {
            PUNTO_UNICO.ESBPUNTOUNICOACCESOService service = new PUNTO_UNICO.ESBPUNTOUNICOACCESOService();
           
            //Envía las Credenciales en el SOAP Header
            HeaderHandlerResolver handlerResolver = new HeaderHandlerResolver();
            service.setHandlerResolver(handlerResolver);           
           
            PUNTO_UNICO.ExecutePpt port = service.getSoapPUNTOUNICOACCESOExecutePpt();
            Detalle DetalleMH = new Detalle();
           
            // TODO initialize WS operation arguments here
            PUNTO_UNICO.BPELSOAPUNTOUNICOProcessRequest bpelSOAPUNTOUNICOProcessRequest = null;           
            bpelSOAPUNTOUNICOProcessRequest.setIDTRANSACCION("1");
            bpelSOAPUNTOUNICOProcessRequest.setTIPOTRAMA("XML");
            bpelSOAPUNTOUNICOProcessRequest.setAchivo(null);
            DetalleMH.setAtributo("NIT");
            DetalleMH.setValor(Nit);           
            bpelSOAPUNTOUNICOProcessRequest.setDetalle(DetalleMH);
           
            // TODO process result here
            PUNTO_UNICO.BPELSOAPUNTOUNICOProcessResponse result = port.execute(bpelSOAPUNTOUNICOProcessRequest);
            msg = result.getDetalle().getValor();
            //System.out.println("Result = "+result);
        } catch (Exception ex) {
            msg = ex.getMessage();
            // TODO handle custom exceptions here
        }
        return "Nit: " + Nit + ", Respuesta: " + msg + " !!!...";
    } 
}

HeaderHandler:
Código: [Seleccionar]
package WSPRUEBA;

import java.util.Set;
import javax.xml.namespace.QName;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;

/**
 *
 * @author www.javadb.com
 */
public class HeaderHandler implements SOAPHandler<SOAPMessageContext> {

    public boolean handleMessage(SOAPMessageContext smc) {

        Boolean outboundProperty = (Boolean) smc.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);

        if (outboundProperty.booleanValue()) {

            SOAPMessage message = smc.getMessage();

            try {

                SOAPEnvelope envelope = smc.getMessage().getSOAPPart().getEnvelope();
                SOAPHeader header = envelope.addHeader();

                SOAPElement security =
                        header.addChildElement("Security", "wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");

                SOAPElement usernameToken =
                        security.addChildElement("UsernameToken", "wsse");
                usernameToken.addAttribute(new QName("xmlns:wsse"), "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");

                SOAPElement username =
                        usernameToken.addChildElement("Username", "wsse");
                username.addTextNode("prueba");

                SOAPElement password =
                        usernameToken.addChildElement("Password", "wsse");
                password.setAttribute("Type", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText");
               password.addTextNode("mipass");

                //Print out the outbound SOAP message to System.out
                message.writeTo(System.out);
                System.out.println("");
               
            } catch (Exception e) {
                e.printStackTrace();
            }

        } else {
            try {
               
                //This handler does nothing with the response from the Web Service so
                //we just print out the SOAP message.
                SOAPMessage message = smc.getMessage();
                message.writeTo(System.out);
                System.out.println("");

            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return outboundProperty;
    }

    public Set getHeaders() {
        //throw new UnsupportedOperationException("Not supported yet.");
        return null;
    }

    public boolean handleFault(SOAPMessageContext context) {
        //throw new UnsupportedOperationException("Not supported yet.");
        return true;
    }

    public void close(MessageContext context) {
    //throw new UnsupportedOperationException("Not supported yet.");
    }
}

HeaderHandlerResolver:
Código: [Seleccionar]
package WSPRUEBA;

import java.util.ArrayList;
import java.util.List;
import javax.xml.ws.handler.Handler;
import javax.xml.ws.handler.HandlerResolver;
import javax.xml.ws.handler.PortInfo;

/**
 *
 * @author www.javadb.com
 */
public class HeaderHandlerResolver implements HandlerResolver {
   
public List<Handler> getHandlerChain(PortInfo portInfo) {
      List<Handler> handlerChain = new ArrayList<Handler>();

      HeaderHandler hh = new HeaderHandler();

      handlerChain.add(hh);

      return handlerChain;
   }
}

No se si algo hago mal o me hace falta algo, he creado Web Services en C# y en Java, tambien los he consumido dentro de mis aplicaciones pero nunca he trabajado con esta medida de seguridad en el SOAP.
« Última Modificación: junio 12, 2013, 12:25:34 pm por NIGHTGHOST »


Desconectado NIGHTGHOST

  • Ghost User -
  • -^- Elite Gold -^-
  • The Communiter-
  • **
  • Mensajes: 1997
  • I'm Sparky... I'm NightWolf... User SVC
(Solucion):Problemas al consumir Web Service
« Respuesta #2 : junio 13, 2013, 05:01:32 pm »
Encontre la solución al problema en C#.net, les comparto la experiencia de este desarrollo por si alguien se topa con el mismo problema:

1- Tuve que instalar el WSE3.0
2- Generar de nuevo el archivo clase del Web Service desde el DOS de la siguiente forma "WseWsdl3.exe /type:webClient http://172.31.11.20:7880/MISERVICIO/MISERVICIO.asmx?WSDL"
3- Una vez se ha anexado la clase al proyecto agregar el siguiente codigo para enviar las credenciales al SOAP HEADER
Código: [Seleccionar]
string Username = "prueba";
string Password = "mipass";
UsernameToken MyToken = new UsernameToken(Username, Password, PasswordOption.SendPlainText);
WSMH.SetClientCredential(MyToken);
Policy MyPolicy = new Policy();
MyPolicy.Assertions.Add(new UsernameOverTransportAssertion());
WSMH.SetPolicy(MyPolicy);

Y santo remedio a estos pinches males... Bueno al menos a nivel de programación, porque en lo personal despues de esta experiencia termine con dolor de espalda y curso XD
« Última Modificación: junio 13, 2013, 05:05:37 pm por NIGHTGHOST »