diff --git a/samples/DotnetIsolated-ClassBased/DotnetIsolated-ClassBased.csproj b/samples/DotnetIsolated-ClassBased/DotnetIsolated-ClassBased.csproj index 96def1e2..e3b78718 100644 --- a/samples/DotnetIsolated-ClassBased/DotnetIsolated-ClassBased.csproj +++ b/samples/DotnetIsolated-ClassBased/DotnetIsolated-ClassBased.csproj @@ -1,6 +1,6 @@ - net6.0 + net8.0 v4 Exe enable @@ -8,10 +8,10 @@ DotnetIsolated_ClassBased - - - - + + + + diff --git a/samples/DotnetIsolated-ClassBased/Functions.cs b/samples/DotnetIsolated-ClassBased/Functions.cs index 804d2565..57f0a6b9 100644 --- a/samples/DotnetIsolated-ClassBased/Functions.cs +++ b/samples/DotnetIsolated-ClassBased/Functions.cs @@ -1,3 +1,4 @@ +using System; using System.Net; using Microsoft.Azure.Functions.Worker; using Microsoft.Azure.Functions.Worker.Http; @@ -21,7 +22,9 @@ public Functions(IServiceProvider serviceProvider, ILogger logger) : public HttpResponseData GetWebPage([HttpTrigger(AuthorizationLevel.Anonymous)] HttpRequestData req) { var response = req.CreateResponse(HttpStatusCode.OK); - response.WriteString(File.ReadAllText("content/index.html")); + string home = Environment.GetEnvironmentVariable("HOME"); + string htmlFilePath = Path.Combine(home, "site", "wwwroot", "content", "index.html"); + response.WriteString(File.ReadAllText(htmlFilePath)); response.Headers.Add("Content-Type", "text/html"); return response; } diff --git a/samples/DotnetIsolated-ClassBased/README.md b/samples/DotnetIsolated-ClassBased/README.md new file mode 100644 index 00000000..037ea923 --- /dev/null +++ b/samples/DotnetIsolated-ClassBased/README.md @@ -0,0 +1,176 @@ +--- +description: This is a chatroom sample that demonstrates bidirectional message pushing between Azure SignalR Service and Azure Functions in a serverless scenario using the Flex Consumption hosting plan and .NET. +page_type: sample +products: +- azure-functions +- azure-signalr-service +- azure +urlFragment: bidirectional-chatroom-sample-charp +languages: +- csharp +--- +# Azure function bidirectional chatroom sample + +This is a chatroom sample that demonstrates bidirectional message pushing between Azure SignalR Service and Azure Functions in a serverless scenario. It leverages the [**upstream**](https://docs.microsoft.com/azure/azure-signalr/concept-upstream) provided by Azure SignalR Service that features proxying messages from client to upstream endpoints in serverless scenario. Azure Functions with SignalR trigger binding allows you to write code to receive and push messages in several languages, including JavaScript, Python, C#, etc. + + - [Prerequisites](#prerequisites) + - [Run sample in Azure](#run-sample-in-azure) + - [Create Azure SignalR Service](#create-azure-signalr-service) + - [Deploy project to Azure Function](#deploy-project-to-azure-function) + - [Use a chat sample website to test end to end](#use-a-chat-sample-website-to-test-end-to-end) + - [Use Key Vault secret reference](#use-key-vault-secret-reference) + - [Enable AAD Token on upstream](#enable-aad-token-on-upstream) + + + +## Prerequisites + +The following are required to build this tutorial. +* [.NET SDK](https://dotnet.microsoft.com/download) (Version 8.0, required for Functions extensions) +* [Azure Functions Core Tools](https://docs.microsoft.com/azure/azure-functions/functions-run-local?tabs=windows%2Ccsharp%2Cbash#install-the-azure-functions-core-tools) (Version 4.0.5907 or newer) +* [Azure CLI](https://docs.microsoft.com/cli/azure/install-azure-cli?view=azure-cli-latest) (Version 2.63.0 or newer) + + + +## Run sample in Azure + +You will create an Azure SignalR Service and an Azure Function app to host the sample. And you will launch chatroom locally but connecting to Azure SignalR Service and Azure Function. + +### Create Azure SignalR Service + +1. Create Azure SignalR Service using `az cli` + + ```bash + resourceGroup=myResourceGroup + signalrName=mySignalRName + region=eastus + + # Create a resource group. + az group create --name $resourceGroup --location $region + + az signalr create -n $signalrName -g $resourceGroup --service-mode Serverless --sku Standard_S1 + # Get connection string for later use. + connectionString=$(az signalr key list -n $signalrName -g $resourceGroup --query primaryConnectionString -o tsv) + ``` + + For more details about creating Azure SignalR Service, see the [tutorial](https://docs.microsoft.com/en-us/azure/azure-signalr/signalr-quickstart-azure-functions-javascript#create-an-azure-signalr-service-instance). + +### Deploy and configure project to Azure Function + +1. Deploy with Azure Functions Core Tools + 1. [Install Azure Functions Core Tools](https://docs.microsoft.com/en-us/azure/azure-functions/functions-run-local?tabs=windows%2Ccsharp%2Cbash#install-the-azure-functions-core-tools) + 2. [Create a Flex Consumption Azure Function App](https://learn.microsoft.com/en-us/azure/azure-functions/flex-consumption-how-to?tabs=azure-cli%2Cvs-code-publish&pivots=programming-language-csharp) (code snippet shown below). This sample can also be used with other Azure Functions hosting plans. + + ```bash + #!/bin/bash + + # Function app and storage account names must be unique. + storageName=mystorageaccount + functionAppName=myserverlessfunc + + # Create an Azure storage account in the resource group. + az storage account create \ + --name $storageName \ + --location $region \ + --resource-group $resourceGroup \ + --sku Standard_LRS + + # Create a serverless function app in the resource group. + az functionapp create \ + --name $functionAppName \ + --storage-account $storageName \ + --flexconsumption-location $region \ + --resource-group $resourceGroup \ + --runtime dotnet-isolated + ``` + 3. Update application settings + + ```bash + az functionapp config appsettings set --resource-group $resourceGroup --name $functionAppName --setting AzureSignalRConnectionString=$connectionString + ``` + + 4. Publish the sample to the Azure Function you created before. + + ```bash + cd /samples/DotnetIsolated-ClassBased + // If prompted function app version, use --force + func azure functionapp publish $functionAppName --dotnet-isolated + ``` + +2. Update Azure SignalR Service Upstream settings + + Open the Azure Portal and nevigate to the Function App created before. Find `signalr_extension` key in the **App keys** blade. + + ![Overview with auth](imgs/getkeys.png) + + Copy the `signalr_extensions` value and use Azure Portal to set the upstream setting. + - In the *Upstream URL Pattern*, fill in the `/runtime/webhooks/signalr?code=` + > [!NOTE] + > The `signalr_extensions` code is required by Azure Function but the trigger does not only use this code but also Azure SignalR Service connection string to validate requests. If you're very serious about the code, use KeyVault secret reference feature to save the code. See [Use Key Vault secret reference](#use-keyvault-secret-reference). + + ![Upstream](imgs/upstream-portal.png) + +### Use a chat sample website to test end to end + +1. Use browser to visit `/api/index` for the web page of the demo. + +2. Try send messages by entering them into the main chat box. + ![Chatroom](imgs/chatroom-noauth.png) + +## Use Key Vault secret reference + +The url of upstream is not encrypted at rest. If you have any sensitive information, you can use Key Vault to save this sensitive information. Basically, you can enable managed identity of Azure SignalR Service and then grant a read permission on a Key Vault instance and use Key Vault reference instead of plaintext in `Upstream URL Pattern`. + +The following steps demonstrate how to use Key Vault secret reference to save `signalr_extensions`. + +1. Enable managed identity. + + 1. Enable managed identity with system assigned identity. + + Open portal and navigate to **Identity**, and switch to **System assigned** page. Switch **Status** to **On**. + + ![SystemAssignedIdentity](imgs/system-assigned-identity.png) + +2. Create a Key Vault instance. + + ```bash + az keyvault create --name "" --resource-group "myResourceGroup" --location "EastUS" + ``` + +3. Save `signalr_extensions` to secret. + + ```bash + az keyvault secret set --name "signalrkey" --vault-name "" --value "" + ``` + +4. Grant **Secret Read** permission to the Key Vault. + + ```bash + az keyvault set-policy --name "" --object-id "" --secret-permissions get + ``` + +5. Get the secret identity of the secret. + + ```bash + az keyvault secret show --name "signalrkey" --vault-name "" --query id -o tsv + ``` + +6. Update **Upstream URL Pattern** with Key Vault reference. You need to follow the syntax `{@Microsoft.KeyVault(SecretUri=)}`. As shown below: + + ![KeyVaultReference](imgs/key-vault-reference.png) + +## Enable AAD Token on upstream + +You can set **ManagedIdentity** as the **Auth** setting in upstream. After that, SignalR Service will set an AAD Token into the `Authorization` for each upstream request. + +1. Make sure you have enabled managed identity. + +2. Click the asterisk in *Hub Rules* and a new page pops out as shown below. + ![Upstream details](imgs/upstream-details-portal.png) + +3. Select *Use Managed Identity* under *Upstream Authentication* and choose the system identity created earlier for the SignalR service. + +4. Use browser to visit `/api/index` for the web page of the demo + +5. Try send messages by entering them into the main chat box. You can verify the `Authorization` has set from the `with Authorization: true` + ![Chatroom](imgs/chatroom.png) \ No newline at end of file diff --git a/samples/DotnetIsolated-ClassBased/content/index.html b/samples/DotnetIsolated-ClassBased/content/index.html index 547b191c..52a3127a 100644 --- a/samples/DotnetIsolated-ClassBased/content/index.html +++ b/samples/DotnetIsolated-ClassBased/content/index.html @@ -99,7 +99,7 @@

Serverless chat

- + @@ -203,9 +203,13 @@

Serverless chat

}; function onNewConnection(message) { data.myConnectionId = message.ConnectionId; + authEnabled = false; + if (message.Authentication) { + authEnabled = true; + } newConnectionMessage = { id: counter++, - text: `${message.ConnectionId} has connected.` + text: `${message.ConnectionId} has connected, with Authorization: ${authEnabled.toString()}` }; data.messages.unshift(newConnectionMessage); } diff --git a/samples/DotnetIsolated-ClassBased/imgs/chatroom-noauth.png b/samples/DotnetIsolated-ClassBased/imgs/chatroom-noauth.png new file mode 100644 index 00000000..12893d8d Binary files /dev/null and b/samples/DotnetIsolated-ClassBased/imgs/chatroom-noauth.png differ diff --git a/samples/DotnetIsolated-ClassBased/imgs/chatroom.png b/samples/DotnetIsolated-ClassBased/imgs/chatroom.png new file mode 100644 index 00000000..e7213530 Binary files /dev/null and b/samples/DotnetIsolated-ClassBased/imgs/chatroom.png differ diff --git a/samples/DotnetIsolated-ClassBased/imgs/cors.png b/samples/DotnetIsolated-ClassBased/imgs/cors.png new file mode 100644 index 00000000..9f5fca82 Binary files /dev/null and b/samples/DotnetIsolated-ClassBased/imgs/cors.png differ diff --git a/samples/DotnetIsolated-ClassBased/imgs/getkeys.png b/samples/DotnetIsolated-ClassBased/imgs/getkeys.png new file mode 100644 index 00000000..f9768fdc Binary files /dev/null and b/samples/DotnetIsolated-ClassBased/imgs/getkeys.png differ diff --git a/samples/DotnetIsolated-ClassBased/imgs/identity.png b/samples/DotnetIsolated-ClassBased/imgs/identity.png new file mode 100644 index 00000000..2e875af1 Binary files /dev/null and b/samples/DotnetIsolated-ClassBased/imgs/identity.png differ diff --git a/samples/DotnetIsolated-ClassBased/imgs/key-vault-reference.png b/samples/DotnetIsolated-ClassBased/imgs/key-vault-reference.png new file mode 100644 index 00000000..b54419b3 Binary files /dev/null and b/samples/DotnetIsolated-ClassBased/imgs/key-vault-reference.png differ diff --git a/samples/DotnetIsolated-ClassBased/imgs/system-assigned-identity.png b/samples/DotnetIsolated-ClassBased/imgs/system-assigned-identity.png new file mode 100644 index 00000000..2a5b7866 Binary files /dev/null and b/samples/DotnetIsolated-ClassBased/imgs/system-assigned-identity.png differ diff --git a/samples/DotnetIsolated-ClassBased/imgs/upstream-details-portal.png b/samples/DotnetIsolated-ClassBased/imgs/upstream-details-portal.png new file mode 100644 index 00000000..341a712a Binary files /dev/null and b/samples/DotnetIsolated-ClassBased/imgs/upstream-details-portal.png differ diff --git a/samples/DotnetIsolated-ClassBased/imgs/upstream-portal.png b/samples/DotnetIsolated-ClassBased/imgs/upstream-portal.png new file mode 100644 index 00000000..7ca03e8a Binary files /dev/null and b/samples/DotnetIsolated-ClassBased/imgs/upstream-portal.png differ