Partilhar via


Authorize requests to Azure SignalR Service resources with Microsoft Entra applications

Azure SignalR Service supports Microsoft Entra ID for authorizing requests with Microsoft Entra applications.

This article explains how to set up your resource and code to authenticate requests to the resource using a Microsoft Entra application.

Register an application in Microsoft Entra ID

The first step is to Register an application in Microsoft Entra ID:

After you register your application, you can find the Application (client) ID and Directory (tenant) ID values on the application's overview page. These GUIDs can be useful in the following steps.

Screenshot of overview information for a registered application.

Add credentials

After registering an app, you can add certificates, client secrets (a string), or federated identity credentials as credentials to your confidential client app registration. Credentials allow your application to authenticate as itself, requiring no interaction from a user at runtime, and are used by confidential client applications that access a web API.

Add role assignments in the Azure portal

As etapas a seguir descrevem como atribuir uma função de Servidor de Aplicativo SignalR a uma entidade de serviço ou uma identidade gerenciada para um recurso do Serviço SignalR do Azure. Para obter etapas detalhadas, consulte Atribuir funções do Azure usando o portal do Azure.

Note

Você pode atribuir uma função a qualquer escopo, incluindo grupo de gerenciamento, assinatura, grupo de recursos ou recurso único. To learn more about scope, see Understand scope for Azure RBAC.

  1. In the Azure portal, go to your Azure SignalR Service resource.

  2. No painel esquerdo, selecione Controlo de acesso (IAM).

  3. Select Add>Add role assignment.

    Screenshot that shows the page for access control and selections for adding a role assignment.

  4. Na guia Função, selecione SignalR App Server. Outras funções internas do Serviço Azure SignalR dependem do seu cenário.

    Funções Description Caso de uso
    Servidor de aplicativos SignalR Acesso às APIs que criam conexões de servidor e geram chaves. Mais comumente usado para um servidor de aplicativos com um recurso do Azure SignalR em execução no modo Padrão.
    Proprietário do Serviço SignalR Acesso total a todas as APIs de plano de dados, incluindo APIs REST, as APIs que criam conexões de servidor e as APIs que geram chaves/tokens. Usado para um servidor de negociação com um recurso do Serviço SignalR do Azure em execução no modo sem servidor. Ele requer permissões de API REST e permissões de API de autenticação.
    Proprietário da API REST do SignalR Acesso total às APIs REST do plano de dados. Usado para o SDK de Gestão do Azure SignalR para gerir conexões e grupos, mas não efetua conexões ao servidor nem trata pedidos de negociação.
    Leitor de API SignalR REST Read-only access to data-plane REST APIs. Usado quando se escreve uma ferramenta de monitorização que chama APIs REST de leitura única.
  5. Selecione Seguinte.

  6. Para a aplicação Microsoft Entra:

    1. Na linha Atribuir acesso a , selecione Usuário, grupo ou entidade de serviço.
    2. Na linha Membros , escolha selecionar membros e, em seguida, escolha a identidade na janela pop-up.
  7. Para identidade gerenciada para recursos do Azure:

    1. Na linha Atribuir acesso a , selecione Identidade gerenciada.
    2. Na linha Membros , escolha selecionar membros e, em seguida, escolha o aplicativo na janela pop-up.
  8. Selecione Seguinte.

  9. Reveja a sua atribuição e, em seguida, selecione Rever + atribuir para confirmar a atribuição de função.

Important

As atribuições de função recém-adicionadas podem levar até 30 minutos para serem propagadas.

Para saber mais sobre como atribuir e gerenciar funções do Azure, consulte:

Configurar o SDK do servidor de aplicativos Microsoft.Azure.SignalR para C#

SDK do servidor Azure SignalR para C#

O SDK do servidor Azure SignalR aproveita a biblioteca Azure.Identity para gerar tokens para conexão com recursos. Clique para explorar usos detalhados.

Note

The tenantId must match the tenantId of the tenant where your SignalR resource is in.

Use Microsoft Entra application with certificate

services.AddSignalR().AddAzureSignalR(option =>
{
    var credential = new ClientCertificateCredential("tenantId", "clientId", "path-to-cert");

    option.Endpoints = [
      new ServiceEndpoint(new Uri(), "https://<resource>.service.signalr.net"), credential);
    ];
});

Use Microsoft Entra application with client secret

services.AddSignalR().AddAzureSignalR(option =>
{
    var credential = new ClientSecretCredential("tenantId", "clientId", "clientSecret");

    option.Endpoints = [
      new ServiceEndpoint(new Uri(), "https://<resource>.service.signalr.net"), credential);
    ];
});

Use Microsoft Entra application with Federated identity

In the case of your organization disabled the usage of client secret/certificate, you can configure the application to trust a managed identity for authentication.

To learn more about it, see Configure an application to trust a managed identity (preview).

Note

Configure an application to trust a managed identity is a preview feature.

services.AddSignalR().AddAzureSignalR(option =>
{
    var msiCredential = new ManagedIdentityCredential("msiClientId");

    var credential = new ClientAssertionCredential("tenantId", "appClientId", async (ctoken) =>
    {
        // Entra ID US Government: api://AzureADTokenExchangeUSGov
        // Entra ID China operated by 21Vianet: api://AzureADTokenExchangeChina
        var request = new TokenRequestContext([$"api://AzureADTokenExchange/.default"]);
        var response = await msiCredential.GetTokenAsync(request, ctoken).ConfigureAwait(false);
        return response.Token;
    });

    option.Endpoints = [
        new ServiceEndpoint(new Uri(), "https://<resource>.service.signalr.net"), credential);
    ];
});

This credential will use the user-assigned managed identity to generate a clientAssertion and use it to exchange for a clientToken for authentication.

The appClientId and tenantId should be the enterprise application that you provisioned in the tenant of SignalR resource.

Use multiple endpoints

Credentials can be different for different endpoints.

In this sample, the Azure SignalR SDK will connect to resource1 with client secret and connect to resource2 with certificate.

services.AddSignalR().AddAzureSignalR(option =>
{
    var credential1 = new ClientSecretCredential("tenantId", "clientId", "clientSecret");
    var credential2 = new ClientCertificateCredential("tenantId", "clientId", "path-to-cert");

    option.Endpoints = new ServiceEndpoint[]
    {
        new ServiceEndpoint(new Uri("https://<resource1>.service.signalr.net"), credential1),
        new ServiceEndpoint(new Uri("https://<resource2>.service.signalr.net"), credential2),
    };
});

Mais exemplos podem ser encontrados neste link de exemplo

Azure SignalR Service bindings in Azure Functions

Azure SignalR Service bindings in Azure Functions use application settings in the portal or local.settings.json locally to configure Microsoft Entra application identities to access your Azure SignalR Service resources.

First, you need to specify the service URI of Azure SignalR Service. The key of the service URI is serviceUri. It starts with a connection name prefix (which defaults to AzureSignalRConnectionString) and a separator. The separator is an underscore (__) in the Azure portal and a colon (:) in the local.settings.json file. You can customize the connection name by using the binding property ConnectionStringSetting. Continue reading to find the sample.

Then, you choose whether to configure your Microsoft Entra application identity in predefined environment variables or in SignalR-specified variables.

Configure an identity in predefined environment variables

See Environment variables for the list of predefined environment variables. When you have multiple services, we recommend that you use the same application identity, so that you don't need to configure the identity for each service. Other services might also use these environment variables, based on the settings of those services.

For example, to use client secret credentials, configure the identity as follows in the local.settings.json file:

{
  "Values": {
    "<CONNECTION_NAME_PREFIX>:serviceUri": "https://<SIGNALR_RESOURCE_NAME>.service.signalr.net",
    "AZURE_CLIENT_ID": "...",
    "AZURE_CLIENT_SECRET": "...",
    "AZURE_TENANT_ID": "..."
  }
}

In the Azure portal, add settings as follows:

 <CONNECTION_NAME_PREFIX>__serviceUri=https://<SIGNALR_RESOURCE_NAME>.service.signalr.net
AZURE_CLIENT_ID = ...
AZURE_TENANT_ID = ...
AZURE_CLIENT_SECRET = ...

Configure an identity in SignalR-specified variables

SignalR-specified variables share the same key prefix with the serviceUri key. Here's the list of variables that you might use:

  • clientId
  • clientSecret
  • tenantId

Here are the samples to use client secret credentials in the local.settings.json file:

{
  "Values": {
    "<CONNECTION_NAME_PREFIX>:serviceUri": "https://<SIGNALR_RESOURCE_NAME>.service.signalr.net",
    "<CONNECTION_NAME_PREFIX>:clientId": "...",
    "<CONNECTION_NAME_PREFIX>:clientSecret": "...",
    "<CONNECTION_NAME_PREFIX>:tenantId": "..."
  }
}

In the Azure portal, add settings as follows:

<CONNECTION_NAME_PREFIX>__serviceUri = https://<SIGNALR_RESOURCE_NAME>.service.signalr.net
<CONNECTION_NAME_PREFIX>__clientId = ...
<CONNECTION_NAME_PREFIX>__clientSecret = ...
<CONNECTION_NAME_PREFIX>__tenantId = ...

Next steps

See the following related articles: