studio
2024.10
false
UiPath logo, featuring letters U and I in white

Guía de usuario de Studio

Última actualización 5 de feb. de 2025

Uso de la autenticación de dos factores dentro de automatizaciones codificadas

Este tutorial muestra cómo incluir código de ejemplo que genere códigos de autenticación de dos factores para tus automatizaciones. Estas son las formas de implementar el código de autenticación de dos factores:
  • Copia y pega el código en un archivo .cs de tu proyecto de destino.
  • Utiliza un archivo NUPKG de ejemplo en tu proyecto.

    Al optar por utilizar el archivo NUPKG de ejemplo, tienes la capacidad de añadir la autenticación de dos factores como actividad dentro de tus archivos XAML.

Consejo: independientemente de si eliges integrar el generador de código de autenticación de dos factores de ejemplo en tus archivos CS (para automatizaciones codificadas) o archivos XAML (para automatizaciones de bajo código), recuerda que puedes invocar una automatización codificada en una de bajo código y viceversa.Para obtener más información sobre las automatizaciones híbridas, consulta Creación de automatizaciones híbridas: combinación de flujos de trabajo codificados y de bajo código.

Copiar y pegar el código en archivos CS

Para utilizar el ejemplo de autenticación de dos factores en tu automatización codificada, puedes copiar y pegar el siguiente código de ejemplo en un archivo CS de tu proyecto de destino.
Nota: el código de ejemplo genera un nuevo código de autenticación cada 30 segundos. Por ejemplo, si se genera un código de autenticación a las 3 horas, 45 minutos y 27 segundos, ese código está disponible durante tres segundos. A continuación, se genera un nuevo código en la marca de 30 segundos.
using System;
using System.Collections.Generic;
using UiPath.CodedWorkflows;
using System.Security.Cryptography;

namespace GenerateTwoFactorAuthenticationCode
{
    public class Workflow : CodedWorkflow
    {
        [Workflow]
        public string Execute(string secretKey)
        {
            return AuthenticationCode(secretKey);
        }

        private string AuthenticationCode(string secret)
        {
            // Step 1: Decode the base32 secret key
            byte[] key = Base32Decode(secret);

            // Step 2: Calculate the time step (current time divided by 30 seconds)
            long unixTime = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
            long timeStep = unixTime / 30;

            // Step 3: Convert time step to byte array (8 bytes, big-endian)
            byte[] timeBytes = BitConverter.GetBytes(timeStep);
            if (BitConverter.IsLittleEndian)
                Array.Reverse(timeBytes);

            // Step 4: Generate HMAC-SHA1 hash using the time step as message and secret key
            using (HMACSHA1 hmac = new HMACSHA1(key))
            {
                byte[] hash = hmac.ComputeHash(timeBytes);

                // Step 5: Extract dynamic binary code (4 bytes) from the hash
                int offset = hash[hash.Length - 1] & 0x0F;
                int binaryCode = (hash[offset] & 0x7F) << 24
                               | (hash[offset + 1] & 0xFF) << 16
                               | (hash[offset + 2] & 0xFF) << 8
                               | (hash[offset + 3] & 0xFF);

                // Step 6: Modulo to get a 6-digit code
                int otp = binaryCode % 1_000_000;

                // Return the OTP as a zero-padded 6-digit string
                return otp.ToString("D6");
            }
        }

        // Base32 decoding function to get the byte array from the base32-encoded key
        private static byte[] Base32Decode(string base32)
        {
            // Decode Base32-encoded string to byte array
            const string base32Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
            int bitBuffer = 0;
            int bitBufferLen = 0;
            var result = new List<byte>();

            foreach (char c in base32.ToUpper())
            {
                if (c == '=') break;

                int index = base32Chars.IndexOf(c);
                if (index < 0) throw new ArgumentException("Invalid Base32 character");

                bitBuffer = (bitBuffer << 5) | index;
                bitBufferLen += 5;

                if (bitBufferLen >= 8)
                {
                    result.Add((byte)(bitBuffer >> (bitBufferLen - 8)));
                    bitBufferLen -= 8;
                }
            }

            return result.ToArray();
        }
    }
}using System;
using System.Collections.Generic;
using UiPath.CodedWorkflows;
using System.Security.Cryptography;

namespace GenerateTwoFactorAuthenticationCode
{
    public class Workflow : CodedWorkflow
    {
        [Workflow]
        public string Execute(string secretKey)
        {
            return AuthenticationCode(secretKey);
        }

        private string AuthenticationCode(string secret)
        {
            // Step 1: Decode the base32 secret key
            byte[] key = Base32Decode(secret);

            // Step 2: Calculate the time step (current time divided by 30 seconds)
            long unixTime = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
            long timeStep = unixTime / 30;

            // Step 3: Convert time step to byte array (8 bytes, big-endian)
            byte[] timeBytes = BitConverter.GetBytes(timeStep);
            if (BitConverter.IsLittleEndian)
                Array.Reverse(timeBytes);

            // Step 4: Generate HMAC-SHA1 hash using the time step as message and secret key
            using (HMACSHA1 hmac = new HMACSHA1(key))
            {
                byte[] hash = hmac.ComputeHash(timeBytes);

                // Step 5: Extract dynamic binary code (4 bytes) from the hash
                int offset = hash[hash.Length - 1] & 0x0F;
                int binaryCode = (hash[offset] & 0x7F) << 24
                               | (hash[offset + 1] & 0xFF) << 16
                               | (hash[offset + 2] & 0xFF) << 8
                               | (hash[offset + 3] & 0xFF);

                // Step 6: Modulo to get a 6-digit code
                int otp = binaryCode % 1_000_000;

                // Return the OTP as a zero-padded 6-digit string
                return otp.ToString("D6");
            }
        }

        // Base32 decoding function to get the byte array from the base32-encoded key
        private static byte[] Base32Decode(string base32)
        {
            // Decode Base32-encoded string to byte array
            const string base32Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
            int bitBuffer = 0;
            int bitBufferLen = 0;
            var result = new List<byte>();

            foreach (char c in base32.ToUpper())
            {
                if (c == '=') break;

                int index = base32Chars.IndexOf(c);
                if (index < 0) throw new ArgumentException("Invalid Base32 character");

                bitBuffer = (bitBuffer << 5) | index;
                bitBufferLen += 5;

                if (bitBufferLen >= 8)
                {
                    result.Add((byte)(bitBuffer >> (bitBufferLen - 8)));
                    bitBufferLen -= 8;
                }
            }

            return result.ToArray();
        }
    }
}

Utiliza un archivo NUPKG de ejemplo

Si deseas utilizar un archivo NUPGK de ejemplo para incluir el código de dos factores en tus automatizaciones, sigue estos pasos:
  1. Descarga el siguiente archivo NUPGK: GenerateTwoFactorAuthenticationCode.nupkg.
  2. Carga el archivo NUPGK descargado en tu host o tenant de Orchestrator, a los que puedes acceder a través de tu instancia de Studio.

    Para obtener más información sobre la carga del archivo NUPGK como biblioteca personalizada en Orchestrator, consulta Cargar manualmente una biblioteca en Orchestrator.

  3. Abre tu proyecto de Studio y abre el menú Gestionar paquetes.
  4. Busca el archivo GenerateTwoFactorAuthenticationCodeNUPKG que guardaste anteriormente en tu fuente de host de Orchestrator o tenant de Orchestrator e instálalo.
    Figura 1. La biblioteca personalizada en el menú Gestionar paquetes

Después de instalar el archivo, navega al panel de Actividades y localiza GenerateTwoFactorAuthenticationCode.Arrastra y suelta la actividad Obtener token 2FA en tus archivos XAML para generar un código de autenticación para tus automatizaciones.
Figura 2. El ejemplo de código GenerateTwoFactorAuthentication en el panel de Actividades

  • Copiar y pegar el código en archivos CS
  • Utiliza un archivo NUPKG de ejemplo

¿Te ha resultado útil esta página?

Obtén la ayuda que necesitas
RPA para el aprendizaje - Cursos de automatización
Foro de la comunidad UiPath
Uipath Logo White
Confianza y seguridad
© 2005-2025 UiPath. Todos los derechos reservados.