Example #1
0
        private static LoginTickets GetLoginTicket(Empresas empresa)
        {
            LoginTickets result = null;
            string       ntpServer;
            NTPClient    ntp;

            if (loginTicketsBL != null)
            {
                result    = loginTicketsBL.GetCurrentLoginTicket(empresa);
                ntpServer = GeneralSettings.Instance.NTPServer;
            }
            if (result == null)
            {
                //Sincronización de reloj por NTP
                ntp = new NTPClient("time.afip.gov.ar");
                ntp.Connect(true);

                XmlDocument         xmlDocument;
                LoginTicketRequests loginTicketRequest;
                //Generacion del Ticket de Requerimiento de Acceso
                if (loginTicketRequestsBL != null)
                {
                    loginTicketRequest = loginTicketRequestsBL.GenerateLoginTicket(empresa);
                    xmlDocument        = loginTicketRequestsBL.GenerateLoginTicketRequestXML(loginTicketRequest);
                }
                else
                {
                    loginTicketRequest = new LoginTicketRequests(empresa);
                    xmlDocument        = GenerateLoginTicketRequestXML(loginTicketRequest);
                }
                // Conversion del XML a bytes
                StringWriter sw = new StringWriter();
                xmlDocument.WriteTo(new XmlTextWriter(sw));
                byte[] loginTicketRequestXml = new ASCIIEncoding().GetBytes(sw.ToString());

                //Firma del Ticket de Requerimiento de Acceso
                X509Certificate2 certOrigen            = GetSenderCertificate(empresa);
                byte[]           loginTicketRequestCMS = Sign(loginTicketRequestXml, certOrigen);

                //Codificacion a base 64
                //string loginTicketRequestBase64 = Convert.ToBase64String(encryptedTicket);
                string loginTicketRequestBase64 = Convert.ToBase64String(loginTicketRequestCMS);

                //Transmisión del Ticket de Requerimiento de Acceso al WSAA
                LoginCMSService loginService = new LoginCMSService();
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
                string loginServiceResponse = loginService.loginCms(loginTicketRequestBase64);

                //Extracción del Ticket de Acceso devuelto por el WSAA
                XmlDocument loginTicketXml = new XmlDocument();
                loginTicketXml.LoadXml(loginServiceResponse);
                if (loginTicketRequestsBL != null)
                {
                    result = loginTicketsBL.GetLoginTicketFromXML(loginTicketXml, loginTicketRequest);
                }
                else
                {
                    result = GetLoginTicketFromXML(loginTicketXml, null);
                }
            }
            return(result);
        }
        private static UInt32 _globalUniqueID = 0; // OJO! NO ES THREAD-SAFE

        /// <summary>
        /// Construye un Login Ticket obtenido del WSAA
        /// </summary>
        /// <param name="argServicio">Servicio al que se desea acceder</param>
        /// <param name="argUrlWsaa">URL del WSAA</param>
        /// <param name="argRutaCertX509Firmante">Ruta del certificado X509 (con clave privada) usado para firmar</param>
        /// <param name="argPassword">Password del certificado X509 (con clave privada) usado para firmar</param>
        /// <param name="argProxy">IP:port del proxy</param>
        /// <param name="argProxyUser">Usuario del proxy</param>'''
        /// <param name="argProxyPassword">Password del proxy</param>
        /// <param name="argVerbose">Nivel detallado de descripcion? true/false</param>
        /// <remarks></remarks>
        public string ObtenerLoginTicketResponse(string argServicio, string argUrlWsaa, string argRutaCertX509Firmante, SecureString argPassword, string argProxy, string argProxyUser, string argProxyPassword, bool argVerbose)
        {
            const string ID_FNC = "[ObtenerLoginTicketResponse]";

            this.RutaDelCertificadoFirmante = argRutaCertX509Firmante;
            this._verboseMode = argVerbose;
            CertificadosX509Lib.VerboseMode = argVerbose;
            string  cmsFirmadoBase64      = null;
            string  loginTicketResponse   = null;
            XmlNode xmlNodoUniqueId       = default(XmlNode);
            XmlNode xmlNodoGenerationTime = default(XmlNode);
            XmlNode xmlNodoExpirationTime = default(XmlNode);
            XmlNode xmlNodoService        = default(XmlNode);

            // PASO 1: Genero el Login Ticket Request
            try
            {
                _globalUniqueID += 1;

                XmlLoginTicketRequest = new XmlDocument();
                XmlLoginTicketRequest.LoadXml(XmlStrLoginTicketRequestTemplate);

                xmlNodoUniqueId                 = XmlLoginTicketRequest.SelectSingleNode("//uniqueId");
                xmlNodoGenerationTime           = XmlLoginTicketRequest.SelectSingleNode("//generationTime");
                xmlNodoExpirationTime           = XmlLoginTicketRequest.SelectSingleNode("//expirationTime");
                xmlNodoService                  = XmlLoginTicketRequest.SelectSingleNode("//service");
                xmlNodoGenerationTime.InnerText = DateTime.Now.AddMinutes(-10).ToString("s");
                xmlNodoExpirationTime.InnerText = DateTime.Now.AddMinutes(+10).ToString("s");
                xmlNodoUniqueId.InnerText       = Convert.ToString(_globalUniqueID);
                xmlNodoService.InnerText        = argServicio;
                this.Service = argServicio;

                if (this._verboseMode)
                {
                    Debug.WriteLine(XmlLoginTicketRequest.OuterXml);
                }
            }
            catch (Exception excepcionAlGenerarLoginTicketRequest)
            {
                throw new Exception(ID_FNC + "***Error GENERANDO el LoginTicketRequest : " + excepcionAlGenerarLoginTicketRequest.Message + excepcionAlGenerarLoginTicketRequest.StackTrace);
            }

            // PASO 2: Firmo el Login Ticket Request
            try
            {
                if (this._verboseMode)
                {
                    Debug.WriteLine(ID_FNC + "***Leyendo certificado: {0}", RutaDelCertificadoFirmante);
                }

                X509Certificate2 certFirmante = CertificadosX509Lib.ObtieneCertificadoDesdeArchivo(RutaDelCertificadoFirmante, argPassword);

                if (this._verboseMode)
                {
                    Debug.WriteLine(ID_FNC + "***Firmando: ");
                    Debug.WriteLine(XmlLoginTicketRequest.OuterXml);
                }

                // Convierto el Login Ticket Request a bytes, firmo el msg y lo convierto a Base64
                Encoding EncodedMsg       = Encoding.UTF8;
                byte[]   msgBytes         = EncodedMsg.GetBytes(XmlLoginTicketRequest.OuterXml);
                byte[]   encodedSignedCms = CertificadosX509Lib.FirmaBytesMensaje(msgBytes, certFirmante);
                cmsFirmadoBase64 = Convert.ToBase64String(encodedSignedCms);
            }
            catch (Exception excepcionAlFirmar)
            {
                throw new Exception(ID_FNC + "***Error FIRMANDO el LoginTicketRequest : " + excepcionAlFirmar.Message);
            }

            // PASO 3: Invoco al WSAA para obtener el Login Ticket Response
            try
            {
                if (this._verboseMode)
                {
                    Debug.WriteLine(ID_FNC + "***Llamando al WSAA en URL: {0}", argUrlWsaa);
                    Debug.WriteLine(ID_FNC + "***Argumento en el request:");
                    Debug.WriteLine(cmsFirmadoBase64);
                }

                LoginCMSService servicioWsaa = new LoginCMSService();
                servicioWsaa.Url = argUrlWsaa;

                // Veo si hay que salir a traves de un proxy
                if (argProxy != null)
                {
                    servicioWsaa.Proxy = new WebProxy(argProxy, true);
                    if (argProxyUser != null)
                    {
                        NetworkCredential Credentials = new NetworkCredential(argProxyUser, argProxyPassword);
                        servicioWsaa.Proxy.Credentials = Credentials;
                    }
                }

                loginTicketResponse = servicioWsaa.loginCms(cmsFirmadoBase64);

                if (this._verboseMode)
                {
                    Debug.WriteLine(ID_FNC + "***LoguinTicketResponse: ");
                    Debug.WriteLine(loginTicketResponse);
                }
            }
            catch (Exception excepcionAlInvocarWsaa)
            {
                throw new Exception(ID_FNC + "***Error INVOCANDO al servicio WSAA : " + excepcionAlInvocarWsaa.Message);
            }

            // PASO 4: Analizo el Login Ticket Response recibido del WSAA
            try
            {
                XmlLoginTicketResponse = new XmlDocument();
                XmlLoginTicketResponse.LoadXml(loginTicketResponse);

                this.UniqueId       = UInt32.Parse(XmlLoginTicketResponse.SelectSingleNode("//uniqueId").InnerText);
                this.GenerationTime = DateTime.Parse(XmlLoginTicketResponse.SelectSingleNode("//generationTime").InnerText);
                this.ExpirationTime = DateTime.Parse(XmlLoginTicketResponse.SelectSingleNode("//expirationTime").InnerText);
                this.Sign           = XmlLoginTicketResponse.SelectSingleNode("//sign").InnerText;
                this.Token          = XmlLoginTicketResponse.SelectSingleNode("//token").InnerText;
            }
            catch (Exception excepcionAlAnalizarLoginTicketResponse)
            {
                throw new Exception(ID_FNC + "***Error ANALIZANDO el LoginTicketResponse : " + excepcionAlAnalizarLoginTicketResponse.Message);
            }
            return(loginTicketResponse);
        }
Example #3
0
        private static uint _globalUniqueID; // OJO! NO ES THREAD-SAFE

        /// <summary>
        /// Construye un Login Ticket obtenido del WSAA
        /// </summary>
        /// <param name="argServicio">Servicio al que se desea acceder</param>
        /// <param name="argUrlWsaa">URL del WSAA</param>
        /// <param name="argRutaCertX509Firmante">Ruta del certificado X509 (con clave privada) usado para firmar</param>
        /// <param name="argPassword">Password del certificado X509 (con clave privada) usado para firmar</param>
        /// <param name="argProxy">IP:port del proxy</param>
        /// <param name="argProxyUser">Usuario del proxy</param>'''
        /// <param name="argProxyPassword">Password del proxy</param>
        /// <param name="argVerbose">Nivel detallado de descripcion? true/false</param>
        /// <remarks></remarks>
        public string ObtenerLoginTicketResponse(string argServicio,
                                                 string argUrlWsaa,
                                                 string argRutaCertX509Firmante,
                                                 SecureString argPassword,
                                                 string argProxy,
                                                 string argProxyUser,
                                                 string argProxyPassword,
                                                 bool argVerbose)
        {
            const string ID_FNC = "[ObtenerLoginTicketResponse]";

            RutaDelCertificadoFirmante = argRutaCertX509Firmante;
            _verboseMode = argVerbose;
            VerboseMode  = argVerbose;

            string cmsFirmadoBase64;
            string loginTicketResponse;

            var xmlFile = Path.Combine(Application.StartupPath, $"{ConfigInfo.CUIT}.xml");

            if (File.Exists(xmlFile))
            {
                XmlLoginTicketResponse = new XmlDocument();
                XmlLoginTicketResponse.Load(xmlFile);

                ExpirationTime = DateTime.Parse(XmlLoginTicketResponse.SelectSingleNode("//expirationTime").InnerText);

                if (ExpirationTime > DateTime.Now.AddSeconds(10))
                {
                    UniqueId       = uint.Parse(XmlLoginTicketResponse.SelectSingleNode("//uniqueId").InnerText);
                    GenerationTime = DateTime.Parse(XmlLoginTicketResponse.SelectSingleNode("//generationTime").InnerText);
                    ExpirationTime = DateTime.Parse(XmlLoginTicketResponse.SelectSingleNode("//expirationTime").InnerText);
                    Sign           = XmlLoginTicketResponse.SelectSingleNode("//sign").InnerText;
                    Token          = XmlLoginTicketResponse.SelectSingleNode("//token").InnerText;

                    return(string.Empty);
                }
            }

            // PASO 1: Genero el Login Ticket Request
            try
            {
                _globalUniqueID += 1;

                XmlLoginTicketRequest = new XmlDocument();
                XmlLoginTicketRequest.LoadXml(XmlStrLoginTicketRequestTemplate);

                var xmlNodoUniqueId       = XmlLoginTicketRequest.SelectSingleNode("//uniqueId");
                var xmlNodoGenerationTime = XmlLoginTicketRequest.SelectSingleNode("//generationTime");
                var xmlNodoExpirationTime = XmlLoginTicketRequest.SelectSingleNode("//expirationTime");
                var xmlNodoService        = XmlLoginTicketRequest.SelectSingleNode("//service");

                xmlNodoGenerationTime.InnerText = DateTime.Now.AddMinutes(-10).ToString("s");
                xmlNodoExpirationTime.InnerText = DateTime.Now.AddMinutes(+10).ToString("s");
                xmlNodoUniqueId.InnerText       = Convert.ToString(_globalUniqueID);
                xmlNodoService.InnerText        = argServicio;
                Service = argServicio;

                if (_verboseMode)
                {
                    Console.WriteLine(XmlLoginTicketRequest.OuterXml);
                }
            }
            catch (Exception excepcionAlGenerarLoginTicketRequest)
            {
                throw new Exception(
                          $"{ID_FNC}***Error GENERANDO el LoginTicketRequest : {excepcionAlGenerarLoginTicketRequest.Message}{excepcionAlGenerarLoginTicketRequest.StackTrace}");
            }

            // PASO 2: Firmo el Login Ticket Request
            try
            {
                if (_verboseMode)
                {
                    Console.WriteLine(ID_FNC + @"***Leyendo certificado: {0}", RutaDelCertificadoFirmante);
                }

                var certFirmante =
                    ObtieneCertificadoDesdeArchivo(RutaDelCertificadoFirmante, argPassword);

                if (_verboseMode)
                {
                    Console.WriteLine($@"{ID_FNC}***Firmando: ");
                    Console.WriteLine(XmlLoginTicketRequest.OuterXml);
                }

                // Convierto el Login Ticket Request a bytes, firmo el msg y lo convierto a Base64
                var EncodedMsg       = Encoding.UTF8;
                var msgBytes         = EncodedMsg.GetBytes(XmlLoginTicketRequest.OuterXml);
                var encodedSignedCms = FirmaBytesMensaje(msgBytes, certFirmante);
                cmsFirmadoBase64 = Convert.ToBase64String(encodedSignedCms);

                Certificado = certFirmante;
            }
            catch (Exception excepcionAlFirmar)
            {
                throw new Exception($"{ID_FNC}***Error FIRMANDO el LoginTicketRequest : {excepcionAlFirmar.Message}");
            }

            // PASO 3: Invoco al WSAA para obtener el Login Ticket Response
            try
            {
                if (_verboseMode)
                {
                    Console.WriteLine($@"{ID_FNC}***Llamando al WSAA en URL: {argUrlWsaa}");
                    Console.WriteLine($@"{ID_FNC}***Argumento en el request:");
                    Console.WriteLine(cmsFirmadoBase64);
                }

                var servicioWsaa = new LoginCMSService
                {
                    Url = argUrlWsaa
                };


                // Veo si hay que salir a traves de un proxy
                if (argProxy != null)
                {
                    servicioWsaa.Proxy = new WebProxy(argProxy, true);

                    if (argProxyUser != null)
                    {
                        var Credentials = new NetworkCredential(argProxyUser, argProxyPassword);
                        servicioWsaa.Proxy.Credentials = Credentials;
                    }
                }

                loginTicketResponse = servicioWsaa.loginCms(cmsFirmadoBase64);

                if (_verboseMode)
                {
                    Console.WriteLine($@"{ID_FNC}***LoguinTicketResponse: ");
                    Console.WriteLine(loginTicketResponse);
                }
            }
            catch (Exception excepcionAlInvocarWsaa)
            {
                throw new Exception($"{ID_FNC}***Error INVOCANDO al servicio WSAA : {excepcionAlInvocarWsaa.Message}");
            }

            // PASO 4: Analizo el Login Ticket Response recibido del WSAA
            try
            {
                XmlLoginTicketResponse = new XmlDocument();
                XmlLoginTicketResponse.LoadXml(loginTicketResponse);
                XmlLoginTicketResponse.Save(xmlFile);

                UniqueId       = uint.Parse(XmlLoginTicketResponse.SelectSingleNode("//uniqueId").InnerText);
                GenerationTime = DateTime.Parse(XmlLoginTicketResponse.SelectSingleNode("//generationTime").InnerText);
                ExpirationTime = DateTime.Parse(XmlLoginTicketResponse.SelectSingleNode("//expirationTime").InnerText);
                Sign           = XmlLoginTicketResponse.SelectSingleNode("//sign").InnerText;
                Token          = XmlLoginTicketResponse.SelectSingleNode("//token").InnerText;
            }
            catch (Exception excepcionAlAnalizarLoginTicketResponse)
            {
                throw new Exception(
                          $"{ID_FNC}***Error ANALIZANDO el LoginTicketResponse : {excepcionAlAnalizarLoginTicketResponse.Message}");
            }

            return(loginTicketResponse);
        }
 public string loginCms(string in0)
 {
     service     = new LoginCMSService();
     service.Url = this.url;
     return(service.loginCms(in0));
 }
Example #5
0
        public void hacerLogin(LoginClass miclaselogin)
        {
            string  cmsFirmadoBase64;
            string  loginTicketResponse;
            XmlNode uniqueIdNode;
            XmlNode generationTimeNode;
            XmlNode ExpirationTimeNode;
            XmlNode ServiceNode;

            try
            {
                _globalId += 1;

                // Preparo el XML Request
                XmlLoginTicketRequest = new XmlDocument();
                XMLLOADER.loadTemplate(XmlLoginTicketRequest, "LoginTemplate");
                uniqueIdNode                 = XmlLoginTicketRequest.SelectSingleNode("//uniqueId");
                generationTimeNode           = XmlLoginTicketRequest.SelectSingleNode("//generationTime");
                ExpirationTimeNode           = XmlLoginTicketRequest.SelectSingleNode("//expirationTime");
                ServiceNode                  = XmlLoginTicketRequest.SelectSingleNode("//service");
                generationTimeNode.InnerText = DateTime.Now.AddMinutes(-10).ToString("s");
                ExpirationTimeNode.InnerText = DateTime.Now.AddMinutes(+10).ToString("s");
                uniqueIdNode.InnerText       = Convert.ToString(_globalId);
                ServiceNode.InnerText        = serv;

                // Obtenemos el Cert
                Certificado = new X509Certificate2();
                if (clave.IsReadOnly())
                {
                    Certificado.Import(File.ReadAllBytes(cert_path), clave, X509KeyStorageFlags.PersistKeySet);
                }
                else
                {
                    Certificado.Import(File.ReadAllBytes(cert_path));
                }

                var msgBytes = Encoding.UTF8.GetBytes(XmlLoginTicketRequest.OuterXml);

                // Firmamos
                var infoContenido = new ContentInfo(msgBytes);
                var cmsFirmado    = new SignedCms(infoContenido);
                var cmsFirmante   = new CmsSigner(Certificado);
                cmsFirmante.IncludeOption = X509IncludeOption.EndCertOnly;
                cmsFirmado.ComputeSignature(cmsFirmante);
                cmsFirmadoBase64 = Convert.ToBase64String(cmsFirmado.Encode());

                // Hago el login

                DatosConfigEmpresa miclaseticket = new DatosConfigEmpresa();



                var    servicio = new LoginCMSService();
                string url      = NegocioConfigEmpresa.urllogin;
                servicio.Url = url;

                if (miclaseticket.verificartiketfiscal() == false)
                {
                    loginTicketResponse = servicio.loginCms(cmsFirmadoBase64);
                    // Analizamos la respuesta
                    XmlLoginTicketResponse = new XmlDocument();
                    XmlLoginTicketResponse.LoadXml(loginTicketResponse);
                    token = XmlLoginTicketResponse.SelectSingleNode("//token").InnerText;
                    sing  = XmlLoginTicketResponse.SelectSingleNode("//sign").InnerText;
                    var exStr  = XmlLoginTicketResponse.SelectSingleNode("//expirationTime").InnerText;
                    var genStr = XmlLoginTicketResponse.SelectSingleNode("//generationTime").InnerText;
                    expirationtime      = DateTime.Parse(exStr);
                    generationtime      = DateTime.Parse(genStr);
                    xdocrequest         = XDocument.Parse(XmlLoginTicketRequest.OuterXml);
                    xdocresponse        = XDocument.Parse(XmlLoginTicketResponse.OuterXml);
                    miclaseticket.Token = token;
                    miclaseticket.Sign  = sing;
                    miclaseticket.Fecha = expirationtime;
                    miclaseticket.agregarticket(miclaseticket);
                }
                else
                {
                    token          = miclaseticket.Token;
                    sing           = miclaseticket.Sign;
                    expirationtime = miclaseticket.Fecha;
                }



                //  MessageBox.Show("Exito");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }