Adición de autenticación a un botAdd authentication to a bot

se aplica a: SDK V4APPLIES TO: SDK v4

El Azure Bot Service SDK v4 facilita el desarrollo de bots que pueden acceder a recursos en línea que requieren autenticación de usuario.The Azure Bot Service v4 SDK facilitates the development of bots that can access online resources that require user authentication. El bot no necesita administrar tokens de autenticación porque Azure lo hace automáticamente mediante OAuth 2.0 para generar un token basado en las credenciales de cada usuario.Your bot does not need to manage authentication tokens because Azure does it for you using OAuth 2.0 to generate a token based on each user's credentials. El bot usa el token generado por Azure para acceder a esos recursos.Your bot uses the token generated by Azure to access those resources. De esta manera, el usuario no tiene que proporcionar el identificador y la contraseña al bot para acceder a un recurso protegido, sino solo a un proveedor de identidades de confianza.In this way, the user does not have to provide ID and password to the bot to access a secured resource but only to a trusted identity provider.

Para obtener información general sobre cómo el Bot Framework controla este tipo de autenticación, vea Autenticación de usuario.For an overview of how the Bot Framework handles this kind of authentication, see User authentication.

Nota

La autenticación también funciona con BotBuilder v3.Authentication also works with BotBuilder v3. Sin embargo, en este artículo solo se describe código de ejemplo de v4.However, this article covers just the v4 sample code.

En este artículo se hace referencia a dos ejemplos.This article references two samples. Uno muestra cómo obtener un token de autenticación.One shows how to obtain an authentication token. El otro es más complejo y muestra cómo acceder a Microsoft Graph en nombre del usuario.The other is more complex and shows how to access Microsoft Graph on behalf of the user. En ambos casos, puede usar Azure Active Directory (AD) v1 o Azure AD v2 como proveedor de identidades para obtener un token de OAuth para el bot.In both cases you can use Azure Active Directory (AD) v1 or Azure AD v2 as an identity provider to obtain an OAuth token for the bot. En este artículo se describen los siguientes procedimientos:This article covers how to:

Una vez que termine este artículo, tendrá un bot que puede responder a algunas tareas sencillas.Once you finish this article, you will have a bot that can respond to a few simple tasks. En el caso del ejemplo de Microsoft Graph, puede enviar un correo electrónico, mostrar quién es y comprobar correos electrónicos recientes.In the case of the Microsoft Graph example, you can send an email, display who you are, and check recent emails. No es necesario publicar el bot para probar las características de OAuth; sin embargo, el bot necesitará un identificador y una contraseña de aplicación de Azure válidos.You do not need to publish the bot to test the OAuth features; however, the bot will need valid Azure app ID and password.

Consideraciones de Web Chat y Direct LineWeb Chat and Direct Line considerations

Importante

Debe usar Direct Line autenticación mejorada habilitada para mitigar los riesgos de seguridad al conectarse a un bot mediante el control Chat en web seguridad.You need to use Direct Line with enhanced authentication enabled to mitigate security risks when connecting to a bot using the Web Chat control. Para obtener más información, vea Direct Line autenticación mejorada.For more information, see Direct Line enhanced authentication.

PrerrequisitosPrerequisites

MuestraSample Versión de BotBuilderBotBuilder version MuestraDemonstrates
Autenticación en C#, JavaScript, Java o PythonAuthentication in C# or JavaScript or Java or Python v4v4 Compatibilidad con OAuthCardOAuthCard support
Autenticación de MSGraph en C#, JavaScript, Java o PythonAuthentication MSGraph in C# or JavaScript or Java or Python v4v4 Compatibilidad de Microsoft Graph API con OAuth 2Microsoft Graph API support with OAuth 2

Información acerca de las muestrasAbout the samples

Para ejecutar los ejemplos a los que se hace referencia en este artículo, necesitará lo siguiente:To run the samples referenced in this article, you need the following:

  1. Una aplicación de Azure Active Directory (AD) para registrar un recurso de bot en Azure.An Azure Active Directory (AD) application to register a bot resource in Azure. Esta aplicación permite que el bot acceda a un recurso protegido externo, como Microsoft Graph.This application allows the bot to access an external secured resource, such as Microsoft Graph. También permite que el usuario se comunique con el bot a través de varios canales, como Chat en web.It also allows the user to communicate with the bot via several channels such as Web Chat.
  2. Una aplicación de Azure AD independiente que funciona como proveedor de identidades.A separate Azure AD application that functions as the identity provider. Esta aplicación proporciona las credenciales necesarias para establecer una conexión de OAuth entre el bot y el recurso protegido.This application provides the credentials needed to establish an OAuth connection between the bot and the secured resource. Tenga en cuenta que en este artículo se usa Active Directory como proveedor de identidades.Notice that this article uses Active Directory as an identity provider. También se admiten muchos otros proveedores.Many other providers are also supported.

Importante

Cuando se registra un bot en Azure, se le asigna una aplicación de Azure AD.Whenever you register a bot in Azure, it gets assigned an Azure AD application. Sin embargo, esta aplicación protege el acceso del canal al bot.However, this application secures channel-to-bot access. Necesita una aplicación de Azure AD adicional para cada recurso protegido externo al que desea que el bot tenga acceso en nombre del usuario.You need an additional Azure AD application for each external secured resource you want the bot to access on behalf of the user.

Crear el recursoCreate the resource

Cree el recurso bot de Azure, que le permitirá registrar el bot con el Azure Bot Service.Create the Azure Bot resource, which will allow you to register your bot with the Azure Bot Service.

Advertencia

El bot de aplicación web y el registro de canales de bot estarán en desuso, pero los recursos existentes seguirán funcionando.Web App Bot and Bot Channels Registration will be deprecated but existing resources will continue to work. En su lugar, debe usar el bot de Azure.You should use Azure Bot, instead.

  1. Vaya a Azure Portal.Go to the Azure portal.

  2. En el panel derecho, seleccione Crear un recurso.In the right pane, select Create a resource.

  3. En el cuadro de búsqueda, escriba bot y presione Entrar.In the search box enter bot, then press Enter.

  4. Seleccione la tarjeta Bot de Azure.Select the Azure Bot card.

    Selección del recurso de bot de Azure

  5. Seleccione Crear.Select Create.

    Creación de un recurso de bot de Azure

  6. Escriba los valores necesarios.Enter the required values. En la ilustración siguiente se muestra la opción Crear nuevo identificador de aplicación de Microsoft seleccionada.The following figure shows Create new Microsoft App ID selected.

    Creación de valores de recursos de bot de Azure

    También puede seleccionar Usar registro de aplicación existente y escribir el identificador y la contraseña de la aplicación existentes.You can also select Use existing app registration and enter your existing app Id and password.

    Creación de valores existentes de recursos de bot de Azure

  7. Seleccione Revisar + crear.Select Review + create.

  8. Si se supera la validación, seleccione Crear.If the validation passes, select Create.

  9. Seleccione Ir al grupo de recursos.Select Go to resource group. Debería ver el bot y los recursos de Azure Key Vault relacionados en el grupo de recursos que seleccionó.You should see the bot and the related Azure Key Vault resources listed in the resource group you selected.

    Sugerencia

    El secreto de la aplicación (contraseña) se almacena en el almacén de claves y hay un almacén de claves por grupo de recursos.The app secret (password) is stored in the the key vault and there is one key vault per resource group. Se recomienda usar el almacén de claves en lugar de copiar y almacenar datos confidenciales.Using key vault is recommended instead of copying and storing sensitive data.

  10. Seleccione Get the SDK from Github (Obtener el SDK de GitHub) para compilar el bot con el SDK Bot Framework sdk.Select Get the SDK from Github to build your bot with the Bot Framework SDK.

    Creación de un bot en el SDK

Azure Key VaultAzure Key Vault

Cuando Azure crea el recurso bot de Azure, también genera un identificador de aplicación y una contraseña, y almacena la contraseña en Azure Key Vault.When Azure creates the Azure Bot resource, it also generates an app Id and a password and stores the password in Azure Key Vault.

Key Vault es un servicio que proporciona administración centralizada de secretos, con control total sobre las directivas de acceso y el historial de auditoría.Key Vault is a service that provides centralized secrets management, with full control over access policies and audit history. Para más información, consulte Uso de referencias de Key Vault para App Service y Azure Functions.For more information, see Use Key Vault references for App Service and Azure Functions. Tenga en cuenta que se le cobrará una pequeña cuota por usar el servicio.Note that you will be charged a small fee for using the service. Para más información, vea Precios de Key Vault.For more information, see Key Vault pricing.

Id. de aplicación y contraseñaApp Id and password

Necesita el identificador y la contraseña de la aplicación de recursos del bot de Azure para configurar el bot para la implementación. You need the Azure bot resource app Id and password to configure your bot for deployment. Asignará sus valores a las variables relacionadas: MicrosoftAppId y MicrosoftAppPassword contenidas en el archivo de configuración del proyecto de bot.You will assign their values to the related variables: MicrosoftAppId and MicrosoftAppPassword contained in your bot project configuration file. El archivo difiere en función del lenguaje de programación que use para crear el bot, como se muestra a continuación.The file differs depending on the programming language you use to create the bot, as shown below.

El appsettings.json archivo contiene esta configuración:The appsettings.json file contains these settings:

{
  "MicrosoftAppId": "<your app id>",
  "MicrosoftAppPassword": "<your password>"
}

Obtener el identificador de la aplicación de recursos de bot de AzureGet Azure bot resource app Id

  1. Vaya a Azure Portal.Go to the Azure portal.
  2. Seleccione el recurso del bot de Azure para obtener su identificador de aplicación.Select the Azure bot resource to obtain its app Id.
  3. En el panel izquierdo, en la Configuración, seleccione Configuración.In the left pane, in the Settings section, select Configuration.
  4. Copie y guarde el valor contenido en el cuadro Id. de aplicación de Microsoft.Copy and save the value contained in the Microsoft App ID box.

Obtenga la contraseña del recurso de bot de Azure Azure Key VaultGet Azure bot resource password from Azure Key Vault

Cuando Azure crea el recurso bot de Azure, almacena la contraseña de la aplicación en Azure Key Vault.When Azure creates the Azure Bot resource, it stores the app password in Azure Key Vault. Para obtener información sobre cómo acceder al almacén de claves para obtener la contraseña, consulte:For information on how to access the key vault to obtain your password, see:

Servicio de identidad de Azure ADAzure AD identity service

Azure Active Directory (Azure AD) es un servicio de identidad en la nube que le permite crear aplicaciones que inician sesión de forma segura mediante protocolos estándar del sector como OAuth 2.0.The Azure Active Directory (Azure AD) is a cloud identity service that allows you to build applications that securely sign in users using industry standard protocols like OAuth2.0.

Puede usar uno de estos dos servicios de identidad:You can use one of these two identity services:

  1. Plataforma del desarrollador de Azure AD (v 1.0).Azure AD developer platform (v1.0). También se conoce como punto de conexión de Azure AD v1, que le permite crear aplicaciones que inician sesión de usuario de forma segura con una cuenta profesional o educativa de Microsoft.Also known as the Azure AD v1 endpoint, which allows you to build apps that securely sign in users with a Microsoft work or school account. Para más información, consulte Introducción a Azure Active Directory para desarrolladores (v1.0).For more information, see the Azure Active Directory for developers (v1.0) overview.
  2. Plataforma de identidad de Microsoft (v2.0).Microsoft identity platform (v2.0). También se conoce como punto de conexión de Azure AD v2, que es una evolución de la plataforma de Azure AD (v1.0).Also known as the Azure AD v2 endpoint, which is an evolution of the Azure AD platform (v1.0). Permite crear aplicaciones que inician sesión en todos los proveedores de identidades de Microsoft y obtener tokens para llamar a las API de Microsoft, como Microsoft Graph u otras API que los desarrolladores hayan creado.It allows you to build applications that sign in to all Microsoft identity providers and get tokens to call Microsoft APIs, such as Microsoft Graph, or other APIs that developers have built. Para más información, consulte Introducción a la Plataforma de identidad de Microsoft (v2.0).For more information, see the Microsoft identity platform (v2.0) overview,

Para obtener información sobre las diferencias entre los puntos de conexión v1 y v2, consulte Motivos para actualizar a la Plataforma de identidad de Microsoft (v2.0).For information about the differences between the v1 and v2 endpoints, see Why update to Microsoft identity platform (v2.0)?. Para más información, consulte Plataforma de identidad de Microsoft (antes Azure Active Directory para desarrolladores).For complete information, see Microsoft identity platform (formerly Azure Active Directory for developers).

Creación del proveedor Azure AD identidadesCreate the Azure AD identity provider

En esta sección se muestra cómo crear un proveedor Azure AD identidad que usa OAuth2 para autenticar el bot.This section shows how to create an Azure AD identity provider that uses OAuth2 to authenticate the bot. Puede usar puntos de conexión de Azure AD v1 o Azure AD v2.You can use Azure AD v1 or Azure AD v2 endpoints.

Sugerencia

Deberá crear y registrar la aplicación de Azure AD en un inquilino en el que pueda dar su consentimiento para delegar los permisos solicitados por una aplicación.You will need to create and register the Azure AD application in a tenant in which you can consent to delegate permissions requested by an application.

  1. Abra el panel Azure Active Directory en Azure Portal.Open the Azure Active Directory panel in the Azure portal. Si no está en el inquilino correcto, haga clic en Cambiar directorio para cambiar el inquilino.If you are not in the correct tenant, click Switch directory to switch to the correct tenant. (Para obtener instrucciones sobre cómo crear un inquilino, consulte Acceso al portal y creación de un inquilino).(For instruction on creating a tenant, see Access the portal and create a tenant.)

  2. Abra el panel Registros de aplicaciones.Open the App registrations panel.

  3. En el panel Registros de aplicaciones, haga clic en Nuevo registro.In the App registrations panel, click New registration.

  4. Rellene los campos obligatorios y cree el registro de aplicaciones.Fill in the required fields and create the app registration.

    1. Asigne un nombre a la aplicación.Name your application.

    2. Seleccione los tipos de cuenta admitidos para la aplicación.Select the Supported account types for your application. (Cualquiera de estas opciones funcionará con este ejemplo).(Any of these options will work with this sample.)

    3. Para el URI de redirecciónFor the Redirect URI

      1. Seleccione Web.Select Web.
      2. Establezca la dirección URL en https://token.botframework.com/.auth/web/redirect.Set the URL to https://token.botframework.com/.auth/web/redirect.
    4. Haga clic en Registrar.Click Register.

      • Una vez creada, Azure muestra la página Información general de la aplicación.Once it is created, Azure displays the Overview page for the app.
      • Registre el valor del identificador de aplicación (cliente) .Record the Application (client) ID value. Usará este valor más adelante como identificador de cliente al crear la cadena de conexión y registrar el proveedor de Azure AD con el registro del bot.You will use this value later as the Client id when you create the connection string and register the Azure AD provider with the bot registration.
      • Registre también el valor del identificador de directorio (inquilino) .Also record the Directory (tenant) ID value. También lo usará para registrar esta aplicación de proveedor con el bot.You will also use this to register this provider application with your bot.
  5. En el panel de navegación, haga clic en Certificados y secretos para crear un secreto para la aplicación.In the navigation pane, click Certificates & secrets to create a secret for your application.

    1. En Secretos de cliente, haga clic en Nuevo secreto de cliente.Under Client secrets, click New client secret.
    2. Agregue una descripción para diferenciar a este secreto de otros que puede que tenga que crear para esta aplicación, como bot login.Add a description to identify this secret from others you might need to create for this app, such as bot login.
    3. Establezca la opción Expira en Nunca.Set Expires to Never.
    4. Haga clic en Agregar.Click Add.
    5. Antes de salir de esta página, registre el secreto.Before leaving this page, record the secret. Usará este valor más adelante como Secreto de cliente al registrar la aplicación de Azure AD con el bot.You will use this value later as the Client secret when you register your Azure AD application with your bot.
  6. En el panel de navegación, haga clic en Permisos de API para que se abra el panel Permisos de API.In the navigation pane, click API permissions to open the API permissions panel. Es un procedimiento recomendado establecer explícitamente los permisos de API de la aplicación.It is a best practice to explicitly set the API permissions for the app.

    1. Haga clic en Agregar un permiso para que aparezca el panel Solicitud de permisos de API.Click Add a permission to show the Request API permissions pane.

    2. Para este ejemplo, seleccione Microsoft APIs y Microsoft Graph.For this sample, select Microsoft APIs and Microsoft Graph.

    3. Elija Permisos delegados y asegúrese de que se seleccionan los permisos que necesita.Choose Delegated permissions and make sure the permissions you need are selected. Este ejemplo requiere estos permisos.This sample requires theses permissions.

      Nota

      Los permisos marcados como SE NECESITA EL CONSENTIMIENTO DEL ADMINISTRADOR requerirán un usuario y un administrador de inquilinos para iniciar sesión, por lo que evite usarlos para el bot.Any permission marked as ADMIN CONSENT REQUIRED will require both a user and a tenant admin to login, so for your bot tend to stay away from these.

      • openidopenid
      • profileprofile
      • Mail.ReadMail.Read
      • Mail.SendMail.Send
      • User.ReadUser.Read
      • User.ReadBasic.AllUser.ReadBasic.All
    4. Haga clic en Agregar permisos.Click Add permissions. (La primera vez que un usuario acceda a esta aplicación mediante el bot deberá conceder su consentimiento).(The first time a user accesses this app through the bot, they will need to grant consent.)

Ahora tiene una aplicación de Azure AD configurada.You now have an Azure AD application configured.

Nota

Asignará el identificador de aplicación (cliente) y el secreto de cliente al crear la cadena de conexión y registrar el proveedor de identidades con el registro del bot.You will assign the Application (client) ID and the Client secret, when you create the connection string and register the identity provider with the bot registration. Consulte la siguiente sección.See next section.

Registro del Azure AD de identidades con el botRegister the Azure AD identity provider with the bot

El paso siguiente consiste en registrar la aplicación de Azure AD que acaba de crear con el bot.The next step is to register the Azure AD application that you just created with the bot.

Azure AD v2Azure AD v2

  1. Vaya a la página de registro de canales del bot en Azure Portal.Navigate to your bot's Bot Channels Registration page on the Azure Portal.

  2. Haga clic en Configuración.Click Settings.

  3. En Configuración de conexión de OAuth, cerca de la parte inferior de la página, haga clic en Agregar configuración.Under OAuth Connection Settings near the bottom of the page, click Add Setting.

  4. Rellene el formulario de la siguiente manera:Fill in the form as follows:

    1. Nombre.Name. Escriba un nombre para la conexión.Enter a name for your connection. Lo usará en el código del bot.You'll use it in your bot code.

    2. Proveedor de servicios.Service Provider. Seleccione Azure Active Directory v2.Select Azure Active Directory v2. Después de seleccionar esta opción, se mostrarán los campos específicos de Azure AD.Once you select this, the Azure AD-specific fields will be displayed.

    3. Id. de cliente. Escriba el identificador de aplicación (cliente) que registró para el Azure AD de identidades v2.Client id. Enter the application (client) ID you recorded for your Azure AD v2 identity provider.

    4. Secreto de cliente.Client secret. Escriba el secreto que registró para el proveedor Azure AD de identidades v2.Enter the secret you recorded for your Azure AD v2 identity provider.

    5. Dirección URL Exchange token.Token Exchange URL. Déjelo en blanco porque solo se usa para sso Azure AD v2.Leave it blank because it is used for SSO in Azure AD v2 only.

    6. Id. de inquilino.Tenant ID. Escriba el identificador de directorio (inquilino) que registró anteriormente para la aplicación de AAD o común en función de los tipos de cuenta admitidos seleccionados al crear la aplicación de Azure DD. Enter the directory (tenant) ID that your recorded earlier for your AAD app or common depending on the supported account types selected when you created the Azure DD app. Para decidir qué valor asignar, siga estos criterios:To decide which value to assign follow these criteria:

      • Al crear la aplicación de Azure AD, si seleccionó Solo las cuentas de este directorio organizativo (solo Microsoft: un solo inquilino) , especifique el valor de tenant ID que anotó anteriormente para la aplicación de AAD.When creating the Azure AD app if you selected Accounts in this organizational directory only (Microsoft only - Single tenant) enter the tenant ID you recorded earlier for the AAD app.
      • Sin embargo, si seleccionó Cuentas en cualquier directorio organizativo (cualquier directorio de AAD: multiinquilino y cuentas personales de Microsoft, como Xbox o Outlook.com) o Cuentas en cualquier directorio organizativo (directorio de Microsoft Azure AD: multiinquilino) , escriba la palabra common en lugar de un identificador de inquilino.However, if you selected Accounts in any organizational directory (Any AAD directory - Multi tenant and personal Microsoft accounts e.g. Xbox, Outlook.com) or Accounts in any organizational directory(Microsoft Azure AD directory - Multi tenant) enter the word common instead of a tenant ID. De lo contrario, la aplicación de AAD realizará la verificación en el inquilino cuyo identificador se seleccionó y excluirá las cuentas personales de Microsoft.Otherwise, the AAD app will verify through the tenant whose ID was selected and exclude personal MS accounts.

      Este será el inquilino asociado a los usuarios que se pueden autenticar.This will be the tenant associated with the users who can be authenticated. Para más información, consulte Inquilinos en Azure Active Directory.For more information, see Tenancy in Azure Active Directory.

    7. En Ámbitos, escriba los nombres del permiso que eligió en el registro de la aplicación.For Scopes, enter the names of the permission you chose from the application registration. Con fines de prueba, puede escribir: openid profile .For testing purposes, you can just enter: openid profile.

      Nota

      Para Azure AD v2, el campo Ámbitos toma una lista de valores que distingue mayúsculas de minúsculas, separados por espacios.For Azure AD v2, Scopes field takes a case-sensitive, space-separated list of values.

  5. Haga clic en Save(Guardar).Click Save.

Nota

Estos valores permiten que la aplicación acceda a datos de Office 365 a través de Microsoft Graph API.These values enable your application to access Office 365 data via the Microsoft Graph API. Además, el campo Dirección URL de intercambio de tokens debe dejarse en blanco porque solo se usa para el inicio de sesión único en Azure AD v2.Also, the Token Exchange URL should be left blank because it is used for SSO in Azure AD v2 only.

Prueba de la conexiónTest your connection

  1. Haga clic en la entrada de la conexión para abrir la conexión que acaba de crear.Click on the connection entry to open the connection you just created.
  2. Haga clic en Probar conexión en la parte superior del panel Configuración de conexión del proveedor de servicios.Click Test Connection at the top of the Service Provider Connection Setting pane.
  3. La primera vez, se debería abrir una pestaña del explorador nueva con los permisos que solicita la aplicación y en la que se le pide que acepte.The first time, this should open a new browser tab listing the permissions your app is requesting and prompt you to accept.
  4. Haga clic en Aceptar.Click Accept.
  5. A continuación, se le redirigirá a una página Test Connection to <your-connection-name> Succeeded (Resultado satisfactorio de la prueba de conexión a).This should then redirect you to a Test Connection to <your-connection-name> Succeeded page.

Ahora puede usar este nombre de conexión en el código del bot para recuperar los tokens de usuario.You can now use this connection name in your bot code to retrieve user tokens.

Preparación el código del botPrepare the bot code

Para completar este proceso, necesitará el id. de la aplicación y la contraseña del bot.You will need your bot's app ID and password to complete this process.

  1. Clone el ejemplo con el que desee trabajar del repositorio de GitHub: Autenticación de bot o Autenticación de bot MSGraph.Clone from the github repository the sample you want to work with: Bot authentication or Bot authentication MSGraph.

  2. Actualice appsettings.json:Update appsettings.json:

    • Establezca en ConnectionName el nombre del valor de conexión de OAuth que agregó al bot.Set ConnectionName to the name of the OAuth connection setting you added to your bot.

    • Establezca en MicrosoftAppId y MicrosoftAppPassword el id. de la aplicación y secreto de la aplicación del bot.Set MicrosoftAppId and MicrosoftAppPassword to your bot's app ID and app secret.

      En función de los caracteres del secreto del bot, es posible que sea necesario aplicar secuencias de escape XML a la contraseña.Depending on the characters in your bot secret, you may need to XML escape the password. Por ejemplo, cualquier símbolo de Y comercial (&) tendrá que codificarse como &amp;.For example, any ampersands (&) will need to be encoded as &amp;.

    {
      "MicrosoftAppId": "",
      "MicrosoftAppPassword": "",
      "ConnectionName": ""
    }
    
  3. Actualice startup.cs:Update startup.cs:

    Para usar OAuth en nubes de Azure no públicas, como la nube gubernamental, debe agregar el código siguiente en el startup.cs archivo :To use OAuth in non-public Azure clouds, like government cloud, you must add the following code in the startup.cs file:

    string uri = "https://api.botframework.azure.us";
    MicrosoftAppCredentials.TrustServiceUrl(uri);
    OAuthClientConfig.OAuthEndpoint = uri;
    

Para obtener los valores de Identificador de aplicación de Microsoft y Contraseña de aplicación de Microsoft, consulte Obtención de la contraseña de registro.To obtain the Microsoft app ID and Microsoft app password values, see Get registration password.

Nota

Este código de bot se puede publicar en una suscripción de Azure (para ello, debe hacer clic en el proyecto y seleccionar Publicar), pero para este artículo no es necesario.You could now publish this bot code to your Azure subscription (right-click on the project and choose Publish), but it is not necessary for this article. Tendría que establecer una configuración de publicación que usara la aplicación y el plan de hospedaje que usó durante la configuración del bot en Azure Portal.You would need to set up a publishing configuration that uses the application and hosting plan that you used when configuration the bot in the Azure portal.

Pruebe el bot mediante el EmulatorTest the bot using the Emulator

Si aún no lo ha hecho, instale Bot Framework Emulator.If you have not done so already, install the Bot Framework Emulator. Consulte también Depurar con el Emulator.See also Debug with the Emulator.

Para que el inicio de sesión de ejemplo del bot funcione, debe configurar el Emulator como se muestra en Configuración de la Emulator para la autenticación.In order for the bot sample login to work you must configure the Emulator as shown in Configure the Emulator for authentication.

PruebaTesting

Después de haber configurado el mecanismo de autenticación, puede realizar las pruebas del bot de ejemplo.After you have configured the authentication mechanism, you can perform the actual bot sample testing.

Nota

Es posible que se le pida que escriba un código magic debido a la manera en que se implementa el ejemplo de bot.You may be asked to enter a magic code, because the way the bot sample is implemented. Este código magic forma parte de la especificación RFC 7636 y aporta un elemento de seguridad adicional.This magic code is part of the RFC#7636 and is there to add an extra security element. Al quitar el código magic, aumenta el riesgo para la seguridad.By removing the magic code, there is an increased security risk. Esto se puede mitigar mediante Direct Line con la autenticación mejorada habilitada.This can be mitigated using Direct Line with enhanced authentication enabled. Para obtener más información, vea Bot Framework autenticación mejorada.For more information, see Bot Framework enhanced authentication.

  1. Ejecute el bot de ejemplo localmente en su máquina.Run the bot sample locally on your machine.
  2. Inicie el emulador.Start the Emulator.
  3. Cuando se conecte al bot, tendrá que especificar el identificador de aplicación y la contraseña del bot.You will need to provide your bot's app ID and password when you connect to the bot.
    • El identificador de aplicación y la contraseña se obtienen del registro de la aplicación en Azure.You get the app ID and the password from the Azure app registration. Son los mismos valores asignados a la aplicación de bot en el archivo appsettings.json o .env.These are the same values you assigned to the bot app in the appsettings.json or .env file. En la Emulator, asigne estos valores en el archivo de configuración o la primera vez que se conecte al bot.In the Emulator, you assign these values in the configuration file or the first time you connect to the bot.
    • Si necesita aplicar secuencias de escape XML a la contraseña en el código de bot, también debe hacerlo aquí.If you needed to XML-escape the password in your bot code, you also need to do so here.
  4. Escriba help para ver una lista de los comandos disponibles para el bot y probar las características de autenticación.Type help to see a list of available commands for the bot, and test the authentication features.
  5. Una vez que haya iniciado sesión, no es necesario que vuelva a proporcionar las credenciales hasta que cierre la sesión.Once you've signed in, you don't need to provide your credentials again until you sign out.
  6. Para cerrar la sesión y cancelar la autenticación, escriba logout.To sign out, and cancel your authentication, type logout.

Nota

La autenticación del bot requiere el uso de Bot Connector Service.Bot authentication requires use of the Bot Connector Service. El servicio accede a la información de registro de canales del bot.The service accesses the bot channels registration information for your bot.

Ejemplo de autenticaciónAuthentication example

En el ejemplo de autenticación de un bot, el diálogo está diseñado para recuperar el token del usuario cuando este haya iniciado sesión.In the Bot authentication sample, the dialog is designed to retrieve the user token after the user is logged in.

imagen de prueba del bot de autenticación

Ejemplo de MSGraph de autenticaciónAuthentication MSGraph example

En el ejemplo de autenticación de un bot MSGraph, el diálogo está diseñado para aceptar uyn conjunto limitado de comandos cuando el usuario haya iniciado sesión.In the Bot authentication MSGraph sample, the dialog is designed to accept a limited set of commands after the user is logged in.

Imagen de prueba del bot msgraph


Información adicionalAdditional information

Cuando un usuario le pide al bot que haga algo para lo que es necesario que el usuario haya iniciado sesión, el bot puede usar OAuthPrompt para iniciar la recuperación de un token para una conexión determinada.When a user asks the bot to do something that requires the bot to have the user logged in, the bot can use an OAuthPrompt to initiate retrieving a token for a given connection. OAuthPrompt crea un flujo de recuperación de tokens que consta de:The OAuthPrompt creates a token retrieval flow that consists of:

  1. Comprobación de que Azure Bot Service ya tiene un token para el usuario y la conexión actuales.Checking to see if the Azure Bot Service already has a token for the current user and connection. Si hay un token, este se devuelve.If there is a token, the token is returned.
  2. Si Azure Bot Service no tiene un token almacenado en caché, se crea un elemento OAuthCard que es un botón de inicio de sesión en el que el usuario puede hacer clic.If Azure Bot Service does not have a cached token, an OAuthCard is created which is a sign in button the user can click on.
  3. Después de que el usuario hace clic en el botón de inicio de sesión OAuthCard, Azure Bot Service envía al bot el token del usuario directamente o presenta al usuario un código de autenticación de 6 dígitos para entrar en la ventana de chat.After the user clicks on the OAuthCard sign in button, Azure Bot Service will either send the bot the user's token directly or will present the user with a 6-digit authentication code to enter in the chat window.
  4. Si se presenta al usuario un código de autenticación, el bot intercambia este código de autenticación por el token del usuario.If the user is presented with an authentication code, the bot then exchanges this authentication code for the user's token.

En las secciones siguientes se describe la forma en que el ejemplo implementa algunas tareas de autenticación comunes.The following sections describe how the sample implements some common authentication tasks.

Use un símbolo del sistema de OAuth para que el usuario inicie sesión y obtener un tokenUse an OAuth prompt to sign the user in and get a token

imagen de csharp de arquitectura

Dialogs\MainDialog.csDialogs\MainDialog.cs

Agregue un símbolo del sistema de OAuth a MainDialog en su constructor.Add an OAuth prompt to MainDialog in its constructor. En este caso, el valor del nombre de la conexión se recuperó del archivo appsettings.json.Here, the value for the connection name was retrieved from the appsettings.json file.

AddDialog(new OAuthPrompt(
    nameof(OAuthPrompt),
    new OAuthPromptSettings
    {
        ConnectionName = ConnectionName,
        Text = "Please Sign In",
        Title = "Sign In",
        Timeout = 300000, // User has 5 minutes to login (1000 * 60 * 5)
    }));

En un paso del diálogo, utilice BeginDialogAsync para iniciar el símbolo del sistema de OAuth, que pide al usuario que inicie sesión.Within a dialog step, use BeginDialogAsync to start the OAuth prompt, which asks the user to sign in.

  • Si el usuario ya ha iniciado sesión, se generará un evento de respuesta de token sin preguntar al usuario.If the user is already signed in, this will generate a token response event, without prompting the user.
  • En caso contrario, se le pedirá al usuario que inicie sesión.Otherwise, this will prompt the user to sign in. Azure Bot Service envía el evento de respuesta de token después de que el usuario intenta iniciar sesión.The Azure Bot Service sends the token response event after the user attempts to sign in.
return await stepContext.BeginDialogAsync(nameof(OAuthPrompt), null, cancellationToken);

En el paso siguiente del diálogo, compruebe la presencia de un token en el resultado del paso anterior.Within the following dialog step, check for the presence of a token in the result from the previous step. Si no es NULL, significa que el usuario iniciado sesión correctamente.If it is not null, the user successfully signed in.

// Get the token from the previous step. Note that we could also have gotten the
// token directly from the prompt itself. There is an example of this in the next method.
var tokenResponse = (TokenResponse)stepContext.Result;

Esperar a TokenResponseEventWait for a TokenResponseEvent

Cuando se inicia un símbolo del sistema de OAuth, espera un evento de respuesta del token del que recuperará el token del usuario.When you start an OAuth prompt, it waits for a token response event, from which it will retrieve the user's token.

Bots\AuthBot.csBots\AuthBot.cs

AuthBot deriva de ActivityHandler y controla explícitamente las actividades del evento de respuesta del token.AuthBot derives from ActivityHandler and explicitly handles token response event activities. En este caso, seguimos con el diálogo activo, lo que permite que el símbolo del sistema de OAuth procese el evento y recupere el token.Here, we continue the active dialog, which allows the OAuth prompt to process the event and retrieve the token.

protected override async Task OnTokenResponseEventAsync(ITurnContext<IEventActivity> turnContext, CancellationToken cancellationToken)
{
    Logger.LogInformation("Running dialog with Token Response Event Activity.");

    // Run the Dialog with the new Token Response Event Activity.
    await Dialog.RunAsync(turnContext, ConversationState.CreateProperty<DialogState>(nameof(DialogState)), cancellationToken);
}

Cierre de la sesión del usuarioLog the user out

Es recomendable permitir a los usuarios cerrar sesión de forma explícita, en lugar de depender de que se agote el tiempo de espera de la conexión.It is best practice to let users explicitly sign out or logout, instead of relying on the connection to time out.

Dialogs\LogoutDialog.csDialogs\LogoutDialog.cs

private async Task<DialogTurnResult> InterruptAsync(DialogContext innerDc, CancellationToken cancellationToken = default(CancellationToken))
{
    if (innerDc.Context.Activity.Type == ActivityTypes.Message)
    {
        var text = innerDc.Context.Activity.Text.ToLowerInvariant();

        if (text == "logout")
        {
            // The UserTokenClient encapsulates the authentication processes.
            var userTokenClient = innerDc.Context.TurnState.Get<UserTokenClient>();
            await userTokenClient.SignOutUserAsync(innerDc.Context.Activity.From.Id, ConnectionName, innerDc.Context.Activity.ChannelId, cancellationToken).ConfigureAwait(false);

            await innerDc.Context.SendActivityAsync(MessageFactory.Text("You have been signed out."), cancellationToken);
            return await innerDc.CancelAllDialogsAsync(cancellationToken);
        }
    }

    return null;
}

Incorporación de la autenticación de TeamsAdding Teams Authentication

Teams se comporta de forma ligeramente diferente a otros canales en lo que respecta a OAuth y requiere algunos cambios para implementar correctamente la autenticación.Teams behaves somewhat differently than other channels in regards to OAuth and requires a few changes to properly implement authentication. Agregaremos código del ejemplo de bot deautenticación Teams ( / JavaScript java deC#). / We will add code from the Teams Authentication Bot sample (C#/JavaScript/Java).

Una diferencia entre otros canales y Teams es que Teams envía una actividad de invocación al bot, en lugar de una actividad de evento.One difference between other channels and Teams is that Teams sends an invoke activity to the bot, rather than an event activity.

Bots/TeamsBot.csBots/TeamsBot.cs

protected override async Task OnTeamsSigninVerifyStateAsync(ITurnContext<IInvokeActivity> turnContext, CancellationToken cancellationToken)
{
    Logger.LogInformation("Running dialog with signin/verifystate from an Invoke Activity.");

    // The OAuth Prompt needs to see the Invoke Activity in order to complete the login process.

    // Run the Dialog with the new Invoke Activity.
    await Dialog.RunAsync(turnContext, ConversationState.CreateProperty<DialogState>(nameof(DialogState)), cancellationToken);
}

Si usa un símbolo del sistema de OAuth, esta actividad de invocación se debe reenviar al diálogo.If you use an OAuth prompt, this invoke activity must be forwarded to the dialog. Lo haremos en TeamsActivityHandler.We will do so in the TeamsActivityHandler. Agregue el siguiente código al archivo de diálogo principal.Add the following code to your main dialog file.

Bots/DialogBot.csBots/DialogBot.cs

public class DialogBot<T> : TeamsActivityHandler where T : Dialog

Por último, asegúrese de agregar un archivo TeamsActivityHandler adecuado (TeamsActivityHandler.cs para los bots de C# y teamsActivityHandler.js para bots de JavaScript) en el nivel superior de la carpeta del bot.Finally, make sure to add an appropriate TeamsActivityHandler file (TeamsActivityHandler.cs for C# bots and teamsActivityHandler.js for Javascript bots) at the topmost level in your bot's folder.

También TeamsActivityHandler envía actividades de reacción de mensajes.The TeamsActivityHandler also sends message reaction activities. Una actividad de reacción de mensaje hace referencia a la actividad original mediante el campo reply to ID (responder a id.).A message reaction activity references the original activity using the reply to ID field. Esta actividad también debe ser visible mediante la fuente de actividades de Microsoft Teams.This activity should also be visible through the Activity Feed in Microsoft Teams.

Nota

Debe crear un manifiesto e incluir token.botframework.com en la sección validDomains. En caso contrario, el botón Iniciar sesión de OAuthCard no abrirá la ventana de autenticación.You need to create a manifest and include token.botframework.com in the validDomains section; otherwise the OAuthCard Sign in button will not open the authentication window. Use App Studio para generar el manifiesto.Use the App Studio to generate your manifest.

Lecturas adicionalesFurther reading