From 745ce48c4d89e2b4fe7ece07bd677f861068340f Mon Sep 17 00:00:00 2001 From: Luke Latham <1622880+guardrex@users.noreply.github.com> Date: Wed, 29 Jan 2025 07:51:52 -0500 Subject: [PATCH 1/3] Clarification on using the `@` prefix (#34570) --- aspnetcore/blazor/components/index.md | 77 +++++++++++++++------------ 1 file changed, 44 insertions(+), 33 deletions(-) diff --git a/aspnetcore/blazor/components/index.md b/aspnetcore/blazor/components/index.md index bd693bb7798b..bdbecf3fb396 100644 --- a/aspnetcore/blazor/components/index.md +++ b/aspnetcore/blazor/components/index.md @@ -727,45 +727,54 @@ The `Heading` component example shown in this section doesn't have an [`@page`][ ## Component parameters -*Component parameters* pass data to components and are defined using public [C# properties](/dotnet/csharp/programming-guide/classes-and-structs/properties) on the component class with the [`[Parameter]` attribute](xref:Microsoft.AspNetCore.Components.ParameterAttribute). In the following example, a built-in reference type () and a user-defined reference type (`PanelBody`) are passed as component parameters. +*Component parameters* pass data to components and are defined using public [C# properties](/dotnet/csharp/programming-guide/classes-and-structs/properties) on the component class with the [`[Parameter]` attribute](xref:Microsoft.AspNetCore.Components.ParameterAttribute). -`PanelBody.cs`: +In the following `ParameterChild` component, component parameters include: -:::moniker range=">= aspnetcore-9.0" +* Built-in reference types. -:::code language="csharp" source="~/../blazor-samples/9.0/BlazorSample_BlazorWebApp/PanelBody.cs"::: + * to pass a title in `Title`. + * to pass a count in `Count`. -:::moniker-end +* A user-defined reference type (`PanelBody`) to pass a Bootstrap card body in `Body`. -:::moniker range=">= aspnetcore-8.0 < aspnetcore-9.0" + `PanelBody.cs`: -:::code language="csharp" source="~/../blazor-samples/8.0/BlazorSample_BlazorWebApp/PanelBody.cs"::: + :::moniker range=">= aspnetcore-9.0" -:::moniker-end + :::code language="csharp" source="~/../blazor-samples/9.0/BlazorSample_BlazorWebApp/PanelBody.cs"::: -:::moniker range=">= aspnetcore-7.0 < aspnetcore-8.0" + :::moniker-end -:::code language="csharp" source="~/../blazor-samples/7.0/BlazorSample_WebAssembly/PanelBody.cs"::: + :::moniker range=">= aspnetcore-8.0 < aspnetcore-9.0" -:::moniker-end + :::code language="csharp" source="~/../blazor-samples/8.0/BlazorSample_BlazorWebApp/PanelBody.cs"::: -:::moniker range=">= aspnetcore-6.0 < aspnetcore-7.0" + :::moniker-end -:::code language="csharp" source="~/../blazor-samples/6.0/BlazorSample_WebAssembly/PanelBody.cs"::: + :::moniker range=">= aspnetcore-7.0 < aspnetcore-8.0" -:::moniker-end + :::code language="csharp" source="~/../blazor-samples/7.0/BlazorSample_WebAssembly/PanelBody.cs"::: -:::moniker range=">= aspnetcore-5.0 < aspnetcore-6.0" + :::moniker-end -:::code language="csharp" source="~/../blazor-samples/5.0/BlazorSample_WebAssembly/PanelBody.cs"::: + :::moniker range=">= aspnetcore-6.0 < aspnetcore-7.0" -:::moniker-end + :::code language="csharp" source="~/../blazor-samples/6.0/BlazorSample_WebAssembly/PanelBody.cs"::: -:::moniker range="< aspnetcore-5.0" + :::moniker-end -:::code language="csharp" source="~/../blazor-samples/3.1/BlazorSample_WebAssembly/PanelBody.cs"::: + :::moniker range=">= aspnetcore-5.0 < aspnetcore-6.0" -:::moniker-end + :::code language="csharp" source="~/../blazor-samples/5.0/BlazorSample_WebAssembly/PanelBody.cs"::: + + :::moniker-end + + :::moniker range="< aspnetcore-5.0" + + :::code language="csharp" source="~/../blazor-samples/3.1/BlazorSample_WebAssembly/PanelBody.cs"::: + + :::moniker-end `ParameterChild.razor`: @@ -808,7 +817,7 @@ The `Heading` component example shown in this section doesn't have an [`@page`][ > [!WARNING] > Providing initial values for component parameters is supported, but don't create a component that writes to its own parameters after the component is rendered for the first time. For more information, see . -The `Title` and `Body` component parameters of the `ParameterChild` component are set by arguments in the HTML tag that renders the instance of the component. The following `ParameterParent` component renders two `ParameterChild` components: +The component parameters of the `ParameterChild` component can be set by arguments in the HTML tag that renders an instance of the `ParameterChild` component. The following `ParameterParent` component renders two `ParameterChild` components: * The first `ParameterChild` component is rendered without supplying parameter arguments. * The second `ParameterChild` component receives values for `Title` and `Body` from the `ParameterParent` component, which uses an [explicit C# expression](xref:mvc/views/razor#explicit-razor-expressions) to set the values of the `PanelBody`'s properties. @@ -864,21 +873,21 @@ The `Title` and `Body` component parameters of the `ParameterChild` component ar The following rendered HTML markup from the `ParameterParent` component shows `ParameterChild` component default values when the `ParameterParent` component doesn't supply component parameter values. When the `ParameterParent` component provides component parameter values, they replace the `ParameterChild` component's default values. > [!NOTE] -> For clarity, rendered CSS style classes aren't shown in the following rendered HTML markup. +> For clarity, most of the rendered CSS style classes and some elements aren't shown in the following rendered HTML markup. The main concept demonstrated by the following example is that the parent component assigned values to the child component using its component parameters. ```html

Child component (without attribute values)

-
-
Set By Child
-
Set by child.
+
Set By Child
+
+

Card content set by child.

Child component (with attribute values)

-
-
Set by Parent
-
Set by parent.
+
Set by Parent
+
+

Set by parent.

``` @@ -893,12 +902,14 @@ The following `ParameterParent2` component displays four instances of the preced * The current local date in long format with , which uses an [implicit C# expression](xref:mvc/views/razor#implicit-razor-expressions). * The `panelData` object's `Title` property. +The fifth `ParameterChild` component instance also sets the `Count` parameter. Note how a `string`-typed parameter requires an `@` prefix to ensure that an expression isn't treated as a string literal. However, `Count` is a nullable integer (), so `Count` can receive the value of `count` without an `@` prefix. You can establish an alternative code convention that requires developers in your organization to always prefix with `@`. Either way, we merely recommend that you adopt a consistent approach for how component parameters are passed in Razor markup. + Quotes around parameter attribute values are optional in most cases per the HTML5 specification. For example, `Value=this` is supported, instead of `Value="this"`. However, we recommend using quotes because it's easier to remember and widely adopted across web-based technologies. Throughout the documentation, code examples: * Always use quotes. Example: `Value="this"`. -* Don't use the `@` prefix with nonliterals unless required. Example: `Count="ct"`, where `ct` is a number-typed variable. `Count="@ct"` is a valid stylistic approach, but the documentation and examples don't adopt the convention. +* Don't use the `@` prefix with nonliterals unless required. Example: `Count="count"`, where `count` is a number-typed variable. `Count="@count"` is a valid stylistic approach, but the documentation and examples don't adopt the convention. * Always avoid `@` for literals, outside of Razor expressions. Example: `IsFixed="true"`. This includes keywords (for example, `this`) and `null`, but you can choose to use them if you wish. For example, `IsFixed="@true"` is uncommon but supported. :::moniker range=">= aspnetcore-9.0" @@ -947,21 +958,21 @@ Throughout the documentation, code examples: > Correct (`Title` is a string parameter, `Count` is a number-typed parameter): > > ```razor -> +> > ``` > > ```razor -> +> > ``` > > Incorrect: > > ```razor -> +> > ``` > > ```razor -> +> > ``` Unlike in Razor pages (`.cshtml`), Blazor can't perform asynchronous work in a Razor expression while rendering a component. This is because Blazor is designed for rendering interactive UIs. In an interactive UI, the screen must always display something, so it doesn't make sense to block the rendering flow. Instead, asynchronous work is performed during one of the [asynchronous lifecycle events](xref:blazor/components/lifecycle). After each asynchronous lifecycle event, the component may render again. The following Razor syntax is **not** supported: From 44e4427774141a22a714c2ac50f77ba736913367 Mon Sep 17 00:00:00 2001 From: Luke Latham <1622880+guardrex@users.noreply.github.com> Date: Wed, 29 Jan 2025 12:44:30 -0500 Subject: [PATCH 2/3] Add AKV approach (#34583) --- ...ount-confirmation-and-password-recovery.md | 98 +++++++++++++++- .../security/blazor-web-app-with-entra.md | 2 +- ...ount-confirmation-and-password-recovery.md | 111 +++++++++++++++++- 3 files changed, 207 insertions(+), 4 deletions(-) diff --git a/aspnetcore/blazor/security/account-confirmation-and-password-recovery.md b/aspnetcore/blazor/security/account-confirmation-and-password-recovery.md index 1218060ef897..20e666e30950 100644 --- a/aspnetcore/blazor/security/account-confirmation-and-password-recovery.md +++ b/aspnetcore/blazor/security/account-confirmation-and-password-recovery.md @@ -43,7 +43,18 @@ Register the `AuthMessageSenderOptions` configuration instance in the `Program` builder.Services.Configure(builder.Configuration); ``` -## Configure a user secret for the provider's security key +## Configure a secret for the email provider's security key + +Receive the email provider's security key from the provider and use it in the following guidance. + +Use either or both of the following approaches to supply the secret to the app: + +* [Secret Manager tool](#secret-manager-tool): The Secret Manager tool stores private data on the local machine and is only used during local development. +* [Azure Key Vault](#azure-key-vault): You can store the secret in a key vault for use in any environment, including for the Development environment when working locally. Some developers prefer to use key vaults for staging and production deployments and use the [Secret Manager tool](#secret-manager-tool) for local development. + +We strongly recommend that you avoid storing secrets in project code or configuration files. Use secure authentication flows, such as either or both of the approaches in this section. + +### Secret Manager tool If the project has already been initialized for the [Secret Manager tool](xref:security/app-secrets), it will already have an app secrets identifier (``) in its project file (`.csproj`). In Visual Studio, you can tell if the app secrets ID is present by looking at the **Properties** panel when the project is selected in **Solution Explorer**. If the app hasn't been initialized, execute the following command in a command shell opened to the project's directory. In Visual Studio, you can use the Developer PowerShell command prompt. @@ -63,6 +74,91 @@ For more information, see . [!INCLUDE[](~/blazor/security/includes/secure-authentication-flows.md)] +### Azure Key Vault + +[Azure Key Vault](https://azure.microsoft.com/products/key-vault/) provides a safe approach for providing the app's client secret to the app. + +To create a key vault and set a secret, see [About Azure Key Vault secrets (Azure documentation)](/azure/key-vault/secrets/about-secrets), which cross-links resources to get started with Azure Key Vault. To implement the code in this section, record the key vault URI and the secret name from Azure when you create the key vault and secret. When you set the access policy for the secret in the **Access policies** panel: + +* Only the **Get** secret permission is required. +* Select the application as the **Principal** for the secret. + +Confirm in the Azure or Entra portal that the app has been granted access to the secret that you created for the email provider key. + +> [!IMPORTANT] +> A key vault secret is created with an expiration date. Be sure to track when a key vault secret is going to expire and create a new secret for the app prior to that date passing. + +Add the following `AzureHelper` class to the server project. The `GetKeyVaultSecret` method retrieves a secret from a key vault. Adjust the namespace (`BlazorSample.Helpers`) to match your project namespace scheme. + +`Helpers/AzureHelper.cs`: + +```csharp +using Azure; +using Azure.Identity; +using Azure.Security.KeyVault.Secrets; + +namespace BlazorSample.Helpers; + +public static class AzureHelper +{ + public static string GetKeyVaultSecret(string tenantId, string vaultUri, string secretName) + { + DefaultAzureCredentialOptions options = new() + { + // Specify the tenant ID to use the dev credentials when running the app locally + // in Visual Studio. + VisualStudioTenantId = tenantId, + SharedTokenCacheTenantId = tenantId + }; + + var client = new SecretClient(new Uri(vaultUri), new DefaultAzureCredential(options)); + var secret = client.GetSecretAsync(secretName).Result; + + return secret.Value.Value; + } +} +``` + +Where services are registered in the server project's `Program` file, obtain and bind the secret with [Options configuration](xref:fundamentals/configuration/options): + +```csharp +var tenantId = builder.Configuration.GetValue("AzureAd:TenantId")!; +var vaultUri = builder.Configuration.GetValue("AzureAd:VaultUri")!; + +var emailAuthKey = AzureHelper.GetKeyVaultSecret( + tenantId, vaultUri, "EmailAuthKey"); + +var authMessageSenderOptions = + new AuthMessageSenderOptions() { EmailAuthKey = emailAuthKey }; +builder.Configuration.GetSection(authMessageSenderOptions.EmailAuthKey) + .Bind(authMessageSenderOptions); +``` + +If you wish to control the environment where the preceding code operates, for example to avoid running the code locally because you've opted to use the [Secret Manager tool](#secret-manager-tool) for local development, you can wrap the preceding code in a conditional statement that checks the environment: + +```csharp +if (!context.HostingEnvironment.IsDevelopment()) +{ + ... +} +``` + +In the `AzureAd` section of `appsettings.json` in the server project, confirm the presence of the app's Entra ID `TenantId` and add the following `VaultUri` configuration key and value, if it isn't already present: + +```json +"VaultUri": "{VAULT URI}" +``` + +In the preceding example, the `{VAULT URI}` placeholder is the key vault URI. Include the trailing slash on the URI. + +Example: + +```json +"VaultUri": "https://contoso.vault.azure.net/" +``` + +Configuration is used to facilitate supplying dedicated key vaults and secret names based on the app's environmental configuration files. For example, you can supply different configuration values for `appsettings.Development.json` in development, `appsettings.Staging.json` when staging, and `appsettings.Production.json` for the production deployment. For more information, see . + ## Implement `IEmailSender` The following example is based on Mailchimp's Transactional API using [Mandrill.net](https://www.nuget.org/packages/Mandrill.net). For a different provider, refer to their documentation on how to implement sending an email message. diff --git a/aspnetcore/blazor/security/blazor-web-app-with-entra.md b/aspnetcore/blazor/security/blazor-web-app-with-entra.md index 5c4fbfedfd54..7dec9b1d4b1e 100644 --- a/aspnetcore/blazor/security/blazor-web-app-with-entra.md +++ b/aspnetcore/blazor/security/blazor-web-app-with-entra.md @@ -156,7 +156,7 @@ To create a key vault and set a client secret, see [About Azure Key Vault secret > [!IMPORTANT] > A key vault secret is created with an expiration date. Be sure to track when a key vault secret is going to expire and create a new secret for the app prior to that date passing. -The following `GetKeyVaultSecret` method retrieves a secret from a key vault. Add this method to the server project. Adjust the namespace (`BlazorSample.Helpers`) to match your project namespace scheme. +Add the following `AzureHelper` class to the server project. The `GetKeyVaultSecret` method retrieves a secret from a key vault. Adjust the namespace (`BlazorSample.Helpers`) to match your project namespace scheme. `Helpers/AzureHelper.cs`: diff --git a/aspnetcore/blazor/security/webassembly/standalone-with-identity/account-confirmation-and-password-recovery.md b/aspnetcore/blazor/security/webassembly/standalone-with-identity/account-confirmation-and-password-recovery.md index 31074109a48c..c97e04cbc00e 100644 --- a/aspnetcore/blazor/security/webassembly/standalone-with-identity/account-confirmation-and-password-recovery.md +++ b/aspnetcore/blazor/security/webassembly/standalone-with-identity/account-confirmation-and-password-recovery.md @@ -50,7 +50,18 @@ Register the `AuthMessageSenderOptions` configuration instance in the server pro builder.Services.Configure(builder.Configuration); ``` -## Configure a user secret for the provider's security key +## Configure a secret for the email provider's security key + +Receive the email provider's security key from the provider and use it in the following guidance. + +Use either or both of the following approaches to supply the secret to the app: + +* [Secret Manager tool](#secret-manager-tool): The Secret Manager tool stores private data on the local machine and is only used during local development. +* [Azure Key Vault](#azure-key-vault): You can store the secret in a key vault for use in any environment, including for the Development environment when working locally. Some developers prefer to use key vaults for staging and production deployments and use the [Secret Manager tool](#secret-manager-tool) for local development. + +We strongly recommend that you avoid storing secrets in project code or configuration files. Use secure authentication flows, such as either or both of the approaches in this section. + +## Secret Manager Tool If the server project has already been initialized for the [Secret Manager tool](xref:security/app-secrets), it will already have a app secrets identifier (``) in its project file (`.csproj`). In Visual Studio, you can tell if the app secrets ID is present by looking at the **Properties** panel when the project is selected in **Solution Explorer**. If the app hasn't been initialized, execute the following command in a command shell opened to the server project's directory. In Visual Studio, you can use the Developer PowerShell command prompt (use the `cd` command to change the directory to the server project after you open the command shell). @@ -70,6 +81,102 @@ For more information, see . [!INCLUDE[](~/blazor/security/includes/secure-authentication-flows.md)] +### Azure Key Vault + +[Azure Key Vault](https://azure.microsoft.com/products/key-vault/) provides a safe approach for providing the app's client secret to the app. + +To create a key vault and set a secret, see [About Azure Key Vault secrets (Azure documentation)](/azure/key-vault/secrets/about-secrets), which cross-links resources to get started with Azure Key Vault. To implement the code in this section, record the key vault URI and the secret name from Azure when you create the key vault and secret. When you set the access policy for the secret in the **Access policies** panel: + +* Only the **Get** secret permission is required. +* Select the application as the **Principal** for the secret. + +Confirm in the Azure or Entra portal that the app has been granted access to the secret that you created for the email provider key. + +> [!IMPORTANT] +> A key vault secret is created with an expiration date. Be sure to track when a key vault secret is going to expire and create a new secret for the app prior to that date passing. + +If Microsoft Identity packages aren't already part of the app's package registrations, add the following packages to the server project for Azure Identity and Azure Key Vault. These packages are transitively provided by Microsoft Identity Web packages, so you only need to add them if the app isn't referencing [`Microsoft.Identity.Web`](https://www.nuget.org/packages/Microsoft.Identity.Web): + +* [`Azure.Identity`](https://www.nuget.org/packages/Azure.Identity) +* [`Azure.Security.KeyVault.Secrets`](https://www.nuget.org/packages/Azure.Security.KeyVault.Secrets) + +Add the following `AzureHelper` class to the server project. The `GetKeyVaultSecret` method retrieves a secret from a key vault. Adjust the namespace (`BlazorSample.Helpers`) to match your project namespace scheme. + +`Helpers/AzureHelper.cs`: + +```csharp +using Azure.Identity; +using Azure.Security.KeyVault.Secrets; + +namespace BlazorSample.Helpers; + +public static class AzureHelper +{ + public static string GetKeyVaultSecret(string tenantId, string vaultUri, string secretName) + { + DefaultAzureCredentialOptions options = new() + { + // Specify the tenant ID to use the dev credentials when running the app locally + // in Visual Studio. + VisualStudioTenantId = tenantId, + SharedTokenCacheTenantId = tenantId + }; + + var client = new SecretClient(new Uri(vaultUri), new DefaultAzureCredential(options)); + var secret = client.GetSecretAsync(secretName).Result; + + return secret.Value.Value; + } +} +``` + +Where services are registered in the server project's `Program` file, obtain and bind the secret with [Options configuration](xref:fundamentals/configuration/options): + +```csharp +var tenantId = builder.Configuration.GetValue("AzureAd:TenantId")!; +var vaultUri = builder.Configuration.GetValue("AzureAd:VaultUri")!; + +var emailAuthKey = AzureHelper.GetKeyVaultSecret( + tenantId, vaultUri, "EmailAuthKey"); + +var authMessageSenderOptions = + new AuthMessageSenderOptions() { EmailAuthKey = emailAuthKey }; +builder.Configuration.GetSection(authMessageSenderOptions.EmailAuthKey) + .Bind(authMessageSenderOptions); +``` + +If you wish to control the environment where the preceding code operates, for example to avoid running the code locally because you've opted to use the [Secret Manager tool](#secret-manager-tool) for local development, you can wrap the preceding code in a conditional statement that checks the environment: + +```csharp +if (!context.HostingEnvironment.IsDevelopment()) +{ + ... +} +``` + +In the `AzureAd` section, which you may need to add if it isn't already present, of `appsettings.json` in the server project, add the following `TenantId` and `VaultUri` configuration keys and values, if they aren't already present: + +```json +"AzureAd": { + "TenantId": "{TENANT ID}", + "VaultUri": "{VAULT URI}" +} +``` + +In the preceding example: + +* The `{TENANT ID}` placeholder is the app's tenant ID in Azure. +* The `{VAULT URI}` placeholder is the key vault URI. Include the trailing slash on the URI. + +Example: + +```json +"TenantId": "00001111-aaaa-2222-bbbb-3333cccc4444", +"VaultUri": "https://contoso.vault.azure.net/" +``` + +Configuration is used to facilitate supplying dedicated key vaults and secret names based on the app's environmental configuration files. For example, you can supply different configuration values for `appsettings.Development.json` in development, `appsettings.Staging.json` when staging, and `appsettings.Production.json` for the production deployment. For more information, see . + ## Implement `IEmailSender` in the server project The following example is based on Mailchimp's Transactional API using [Mandrill.net](https://www.nuget.org/packages/Mandrill.net). For a different provider, refer to their documentation on how to implement sending an email message. @@ -198,7 +305,7 @@ Enabling account confirmation on a site with users locks out all the existing us Password recovery requires the server app to adopt an email provider in order to send password reset codes to users. Therefore, follow the guidance earlier in this article to adopt an email provider: * [Select and configure an email provider for the server project](#select-and-configure-an-email-provider-for-the-server-project) -* [Configure a user secret for the provider's security key](#configure-a-user-secret-for-the-providers-security-key) +* [Configure a secret for the email provider's security key](#configure-a-secret-for-the-email-providers-security-key) * [Implement `IEmailSender` in the server project](#implement-iemailsender-in-the-server-project) Password recovery is a two-step process: From cf4cd9de86c618f559c619b7f02f2f1d8592797a Mon Sep 17 00:00:00 2001 From: StarNuik Date: Wed, 29 Jan 2025 20:57:47 +0300 Subject: [PATCH 3/3] Update min-web-api.md (#34591) --- aspnetcore/tutorials/min-web-api.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/aspnetcore/tutorials/min-web-api.md b/aspnetcore/tutorials/min-web-api.md index d6d4aaff2f98..ca8139c1db31 100644 --- a/aspnetcore/tutorials/min-web-api.md +++ b/aspnetcore/tutorials/min-web-api.md @@ -618,7 +618,7 @@ public async Task GetAllTodos_ReturnsOkOfTodosResult() ## Prevent over-posting -Currently the sample app exposes the entire `Todo` object. Production apps In production applications, a subset of the model is often used to restrict the data that can be input and returned. There are multiple reasons behind this and security is a major one. The subset of a model is usually referred to as a Data Transfer Object (DTO), input model, or view model. **DTO** is used in this article. +Currently the sample app exposes the entire `Todo` object. In production applications, a subset of the model is often used to restrict the data that can be input and returned. There are multiple reasons behind this and security is a major one. The subset of a model is usually referred to as a Data Transfer Object (DTO), input model, or view model. **DTO** is used in this article. A DTO can be used to: