From 2fce01df64d8550c5cc7fbc773fca0b4b9a51a52 Mon Sep 17 00:00:00 2001 From: Stephen Halter Date: Fri, 22 Sep 2023 11:50:01 -0700 Subject: [PATCH] Add Identity Components to Blazor template (#50722) # Add Identity Components to Blazor template ## Description This adds the option to add Identity Razor Components (`*.razor` files) when using the Blazor project template. This supports the same feature set as the Identity Razor Pages (`*.cshtml` files). We've already done an accessibility pass over these newly added components and this PR includes all the fixes for Accessibility too. As with the Identity Razor Pages, this supports local authentication (with the option to configure external login providers) and Identity management using EF Core. Fixes #48786 ## Customer Impact These Identity Razor Components have been a common request for years as noted above, because it allows Blazor developers to use Identity without needing to add Razor Pages infrastructure which would otherwise be unnecessary and doesn't integrate well with the rest of the app. For example, the Identity Razor Pages to a Blazor app would use a different layout that doesn't match the look and feel of the Razor Components that make up the rest of the app. ## Regression? - [ ] Yes - [x] No ## Risk - [ ] High - [ ] Medium - [x] Low These are template only changes that only affect the brand new Blazor project template. It should have no impact on the project template output unless you opt-in to the individual auth option (other than a [small fix](https://github.com/dotnet/aspnetcore/pull/50722/commits/5462e42a630c26086a7a1276cc230e668f379ee5) to make the `--empty` option produce compileable output with all `InteractivityPlatform` options.) ## Verification - [x] Manual (required) - [x] Automated We're also adding new validation scenarios for vendors to validate periodically. ## Packaging changes reviewed? - [ ] Yes - [ ] No - [x] N/A ---- - [x] Finish user management components for 2fa, external login, personal data, etc... - [x] Add signout link - [x] Verify RegisterOnPersisting gets invoked as expected with the changes from #50625 - [x] Render ShowRecoveryCodes.razor inline rather than via a redirect. - [x] Add baseline tests - [x] Fix BOMs - [x] Validate the template in VS --- src/ProjectTemplates/ProjectTemplates.slnf | 4 +- .../BlazorWeb-CSharp.Client.csproj.in | 1 + .../BlazorWeb-CSharp.csproj.in | 18 +- .../RazorPagesWeb-CSharp.csproj.in | 2 +- .../.template.config/dotnetcli.host.json | 8 +- .../localize/templatestrings.cs.json | 5 + .../localize/templatestrings.de.json | 5 + .../localize/templatestrings.en.json | 11 +- .../localize/templatestrings.es.json | 5 + .../localize/templatestrings.fr.json | 5 + .../localize/templatestrings.it.json | 5 + .../localize/templatestrings.ja.json | 5 + .../localize/templatestrings.ko.json | 5 + .../localize/templatestrings.pl.json | 5 + .../localize/templatestrings.pt-BR.json | 5 + .../localize/templatestrings.ru.json | 5 + .../localize/templatestrings.tr.json | 5 + .../localize/templatestrings.zh-Hans.json | 5 + .../localize/templatestrings.zh-Hant.json | 5 + .../.template.config/template.json | 128 ++++- .../BlazorWeb-CSharp.Client/Pages/Auth.razor | 18 + .../PersistentAuthenticationStateProvider.cs | 29 ++ .../BlazorWeb-CSharp.Client/Program.cs | 10 + .../BlazorWeb-CSharp.Client/UserInfo.cs | 7 + .../BlazorWeb-CSharp.Client/_Imports.razor | 3 + .../Identity/ExternalLoginPicker.razor | 47 ++ .../Components/Identity/LogoutForm.razor | 34 ++ .../Identity/ShowRecoveryCodes.razor | 32 ++ .../Components/Identity/StatusMessage.razor | 29 ++ .../Components/Layout/ManageLayout.razor | 17 + .../Components/Layout/ManageNavMenu.razor | 37 ++ .../Components/Layout/NavMenu.razor | 42 +- .../Components/Layout/NavMenu.razor.css | 22 + .../Pages/Account/ConfirmEmail.razor | 49 ++ .../Pages/Account/ConfirmEmailChange.razor | 64 +++ .../Pages/Account/ExternalLogin.razor | 213 ++++++++ .../Pages/Account/ForgotPassword.razor | 74 +++ .../Account/ForgotPasswordConfirmation.razor | 8 + .../Pages/Account/InvalidPasswordReset.razor | 8 + .../Pages/Account/InvalidUser.razor | 7 + .../Components/Pages/Account/Lockout.razor | 8 + .../Components/Pages/Account/Login.razor | 133 +++++ .../Pages/Account/LoginWith2fa.razor | 109 +++++ .../Pages/Account/LoginWithRecoveryCode.razor | 94 ++++ .../Pages/Account/Manage/ChangePassword.razor | 97 ++++ .../Account/Manage/DeletePersonalData.razor | 85 ++++ .../Pages/Account/Manage/Disable2fa.razor | 68 +++ .../Pages/Account/Manage/Email.razor | 123 +++++ .../Account/Manage/EnableAuthenticator.razor | 174 +++++++ .../Pages/Account/Manage/ExternalLogins.razor | 152 ++++++ .../Manage/GenerateRecoveryCodes.razor | 67 +++ .../Pages/Account/Manage/Index.razor | 80 +++ .../Pages/Account/Manage/PersonalData.razor | 35 ++ .../Account/Manage/ResetAuthenticator.razor | 55 +++ .../Pages/Account/Manage/SetPassword.razor | 88 ++++ .../Manage/TwoFactorAuthentication.razor | 101 ++++ .../Pages/Account/Manage/_Imports.razor | 2 + .../Components/Pages/Account/Register.razor | 176 +++++++ .../Pages/Account/RegisterConfirmation.razor | 67 +++ .../Account/ResendEmailConfirmation.razor | 78 +++ .../Pages/Account/ResetPassword.razor | 108 +++++ .../Account/ResetPasswordConfirmation.razor | 7 + .../Components/Pages/Account/_Imports.razor | 1 + .../Components/Pages/Auth.razor | 13 + .../BlazorWeb-CSharp/Components/Routes.razor | 4 + .../Components/_Imports.razor | 3 + .../Data/ApplicationDbContext.cs | 8 + .../BlazorWeb-CSharp/Data/ApplicationUser.cs | 9 + ...000000000_CreateIdentitySchema.Designer.cs | 268 +++++++++++ .../00000000000000_CreateIdentitySchema.cs | 222 +++++++++ .../ApplicationDbContextModelSnapshot.cs | 265 ++++++++++ ...000000000_CreateIdentitySchema.Designer.cs | 279 +++++++++++ .../00000000000000_CreateIdentitySchema.cs | 224 +++++++++ .../ApplicationDbContextModelSnapshot.cs | 276 +++++++++++ .../BlazorWeb-CSharp/Data/UserAccessor.cs | 26 + ...omponentsEndpointRouteBuilderExtensions.cs | 102 ++++ .../Identity/IdentityRedirectManager.cs | 63 +++ ...RevalidatingAuthenticationStateProvider.cs | 54 +++ ...RevalidatingAuthenticationStateProvider.cs | 106 ++++ ...istingServerAuthenticationStateProvider.cs | 66 +++ .../BlazorWeb-CSharp/Program.Main.cs | 74 ++- .../BlazorWeb-CSharp/Program.cs | 70 ++- .../BlazorWeb-CSharp/BlazorWeb-CSharp/app.db | Bin 0 -> 102400 bytes .../BlazorWeb-CSharp/appsettings.json | 9 + .../BlazorWeb-CSharp/wwwroot/app.css | 6 +- .../.template.config/template.json | 1 - .../.template.config/template.json | 3 +- .../.template.config/template.json | 1 - .../.template.config/template.json | 1 - .../test/Templates.Tests/BaselineTest.cs | 2 +- .../Templates.Tests/template-baselines.json | 455 ++++++++++++++++++ 91 files changed, 5466 insertions(+), 39 deletions(-) create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp.Client/Pages/Auth.razor create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp.Client/PersistentAuthenticationStateProvider.cs create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp.Client/UserInfo.cs create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Identity/ExternalLoginPicker.razor create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Identity/LogoutForm.razor create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Identity/ShowRecoveryCodes.razor create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Identity/StatusMessage.razor create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Layout/ManageLayout.razor create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Layout/ManageNavMenu.razor create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/ConfirmEmail.razor create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/ConfirmEmailChange.razor create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/ExternalLogin.razor create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/ForgotPassword.razor create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/ForgotPasswordConfirmation.razor create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/InvalidPasswordReset.razor create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/InvalidUser.razor create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/Lockout.razor create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/Login.razor create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/LoginWith2fa.razor create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/LoginWithRecoveryCode.razor create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/Manage/ChangePassword.razor create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/Manage/DeletePersonalData.razor create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/Manage/Disable2fa.razor create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/Manage/Email.razor create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/Manage/EnableAuthenticator.razor create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/Manage/ExternalLogins.razor create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/Manage/GenerateRecoveryCodes.razor create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/Manage/Index.razor create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/Manage/PersonalData.razor create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/Manage/ResetAuthenticator.razor create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/Manage/SetPassword.razor create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/Manage/TwoFactorAuthentication.razor create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/Manage/_Imports.razor create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/Register.razor create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/RegisterConfirmation.razor create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/ResendEmailConfirmation.razor create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/ResetPassword.razor create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/ResetPasswordConfirmation.razor create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/_Imports.razor create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Auth.razor create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Data/ApplicationDbContext.cs create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Data/ApplicationUser.cs create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Data/SqlLite/00000000000000_CreateIdentitySchema.Designer.cs create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Data/SqlLite/00000000000000_CreateIdentitySchema.cs create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Data/SqlLite/ApplicationDbContextModelSnapshot.cs create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Data/SqlServer/00000000000000_CreateIdentitySchema.Designer.cs create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Data/SqlServer/00000000000000_CreateIdentitySchema.cs create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Data/SqlServer/ApplicationDbContextModelSnapshot.cs create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Data/UserAccessor.cs create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Identity/Extensions/IdentityComponentsEndpointRouteBuilderExtensions.cs create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Identity/IdentityRedirectManager.cs create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Identity/IdentityRevalidatingAuthenticationStateProvider.cs create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Identity/PersistingRevalidatingAuthenticationStateProvider.cs create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Identity/PersistingServerAuthenticationStateProvider.cs create mode 100644 src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/app.db diff --git a/src/ProjectTemplates/ProjectTemplates.slnf b/src/ProjectTemplates/ProjectTemplates.slnf index 56945fef18d9..a3e1d4b51627 100644 --- a/src/ProjectTemplates/ProjectTemplates.slnf +++ b/src/ProjectTemplates/ProjectTemplates.slnf @@ -65,8 +65,8 @@ "src\\ProjectTemplates\\Web.ItemTemplates\\Microsoft.DotNet.Web.ItemTemplates.csproj", "src\\ProjectTemplates\\Web.ProjectTemplates\\Microsoft.DotNet.Web.ProjectTemplates.csproj", "src\\ProjectTemplates\\test\\Templates.Blazor.Tests\\Templates.Blazor.Tests.csproj", - "src\\ProjectTemplates\\test\\Templates.Blazor.WebAssembly.Tests\\Templates.Blazor.WebAssembly.Tests.csproj", "src\\ProjectTemplates\\test\\Templates.Blazor.WebAssembly.Auth.Tests\\Templates.Blazor.WebAssembly.Auth.Tests.csproj", + "src\\ProjectTemplates\\test\\Templates.Blazor.WebAssembly.Tests\\Templates.Blazor.WebAssembly.Tests.csproj", "src\\ProjectTemplates\\test\\Templates.Mvc.Tests\\Templates.Mvc.Tests.csproj", "src\\ProjectTemplates\\test\\Templates.Tests\\Templates.Tests.csproj", "src\\Razor\\Razor.Runtime\\src\\Microsoft.AspNetCore.Razor.Runtime.csproj", @@ -95,4 +95,4 @@ "src\\SignalR\\server\\SignalR\\src\\Microsoft.AspNetCore.SignalR.csproj" ] } -} +} \ No newline at end of file diff --git a/src/ProjectTemplates/Web.ProjectTemplates/BlazorWeb-CSharp.Client.csproj.in b/src/ProjectTemplates/Web.ProjectTemplates/BlazorWeb-CSharp.Client.csproj.in index 027eeefed22b..829c12db913c 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/BlazorWeb-CSharp.Client.csproj.in +++ b/src/ProjectTemplates/Web.ProjectTemplates/BlazorWeb-CSharp.Client.csproj.in @@ -12,6 +12,7 @@ + diff --git a/src/ProjectTemplates/Web.ProjectTemplates/BlazorWeb-CSharp.csproj.in b/src/ProjectTemplates/Web.ProjectTemplates/BlazorWeb-CSharp.csproj.in index 31be9a845da9..d676d90df723 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/BlazorWeb-CSharp.csproj.in +++ b/src/ProjectTemplates/Web.ProjectTemplates/BlazorWeb-CSharp.csproj.in @@ -4,16 +4,28 @@ ${DefaultNetCoreTargetFramework} enable enable + aspnet-BlazorWeb-CSharp-53bc9b9d-9d6a-45d4-8429-2a2761773502 True BlazorWeb-CSharp `$(AssemblyName.Replace(' ', '_')) - + - - + + + + + + + + + + + + + diff --git a/src/ProjectTemplates/Web.ProjectTemplates/RazorPagesWeb-CSharp.csproj.in b/src/ProjectTemplates/Web.ProjectTemplates/RazorPagesWeb-CSharp.csproj.in index ee04cb442ea1..2ed95f454912 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/RazorPagesWeb-CSharp.csproj.in +++ b/src/ProjectTemplates/Web.ProjectTemplates/RazorPagesWeb-CSharp.csproj.in @@ -4,7 +4,7 @@ ${DefaultNetCoreTargetFramework} enable enable - aspnet-Company.WebApplication1-0ce56475-d1db-490f-8af1-a881ea4fcd2d + aspnet-Company.WebApplication1-53bc9b9d-9d6a-45d4-8429-2a2761773502 True Company.WebApplication1 diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/dotnetcli.host.json b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/dotnetcli.host.json index a8c678b039b3..897cc41741ca 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/dotnetcli.host.json +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/dotnetcli.host.json @@ -21,6 +21,9 @@ "IncludeSampleContent": { "isHidden": true }, + "UseLocalDB": { + "longName": "use-local-db" + }, "Framework": { "longName": "framework" }, @@ -51,5 +54,8 @@ "longName": "use-program-main", "shortName": "" } - } + }, + "usageExamples": [ + "-int auto --auth individual --use-local-db" + ] } diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.cs.json b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.cs.json index 069f5694009b..65699b857548 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.cs.json +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.cs.json @@ -4,6 +4,7 @@ "description": "Šablona projektu pro vytvoření webové aplikace Blazor, která podporuje vykreslování na straně serveru i interaktivitu klienta. Tato šablona se dá použít pro webové aplikace s bohatými dynamickými uživatelskými rozhraními (UI).", "symbols/Framework/description": "Cílová architektura pro projekt", "symbols/Framework/choices/net8.0/description": "Cílový net8.0", + "symbols/UserSecretsId/description": "The ID to use for secrets (use with Individual auth).", "symbols/skipRestore/description": "Pokud se tato možnost zadá, přeskočí automatické obnovení projektu při vytvoření.", "symbols/ExcludeLaunchSettings/description": "Určuje, jestli se má z vygenerované šablony vyloučit soubor launchSettings.json.", "symbols/kestrelHttpPort/description": "Číslo portu, který se má použít pro koncový bod HTTP v souboru launchSettings.json.", @@ -29,6 +30,10 @@ "symbols/IncludeSampleContent/displayName": "_Zahrnout ukázkové stránky", "symbols/IncludeSampleContent/description": "Nastavuje, jestli se mají přidávat ukázkové stránky a styly pro demonstraci základních vzorů použití.", "symbols/Empty/description": "Nastavuje, jestli se mají vynechat ukázkové stránky a styly, které demonstrují základní vzory použití.", + "symbols/auth/choices/None/description": "No authentication", + "symbols/auth/choices/Individual/description": "Individual authentication", + "symbols/auth/description": "The type of authentication to use", + "symbols/UseLocalDB/description": "Whether to use LocalDB instead of SQLite. This option only applies if --auth Individual is specified.", "symbols/AllInteractive/displayName": "_Enable interactive rendering globally throughout the site", "symbols/AllInteractive/description": "Configures whether to make every page interactive by applying an interactive render mode at the top level. If false, pages will use static server rendering by default, and can be marked interactive on a per-page or per-component basis.", "symbols/NoHttps/description": "Určuje, jestli se má protokol HTTPS vypnout. Tato možnost platí jenom v případě, že se pro --auth nepoužívají Individual, IndividualB2C, SingleOrg ani MultiOrg.", diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.de.json b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.de.json index 96805c77240a..e443e2846c5a 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.de.json +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.de.json @@ -4,6 +4,7 @@ "description": "Eine Projektvorlage zum Erstellen einer Blazor-Web-App, die sowohl serverseitiges Rendering als auch Clientinteraktivität unterstützt. Diese Vorlage kann für Web-Apps mit umfangreichen dynamischen Benutzeroberflächen (UIs) verwendet werden.", "symbols/Framework/description": "Das Zielframework für das Projekt.", "symbols/Framework/choices/net8.0/description": "Ziel net8.0", + "symbols/UserSecretsId/description": "The ID to use for secrets (use with Individual auth).", "symbols/skipRestore/description": "Wenn angegeben, wird die automatische Wiederherstellung des Projekts beim Erstellen übersprungen.", "symbols/ExcludeLaunchSettings/description": "Ob launchSettings.json aus der generierten Vorlage ausgeschlossen werden soll.", "symbols/kestrelHttpPort/description": "Portnummer, die für den HTTP Endpunkt in launchSettings.json verwendet werden soll.", @@ -29,6 +30,10 @@ "symbols/IncludeSampleContent/displayName": "_Include Beispielseiten", "symbols/IncludeSampleContent/description": "Konfiguriert, ob Beispielseiten und Stile hinzugefügt werden, um grundlegende Verwendungsmuster zu veranschaulichen.", "symbols/Empty/description": "Konfiguriert, ob Beispielseiten und Formatierungen weggelassen werden sollen, die grundlegende Verwendungsmuster veranschaulichen.", + "symbols/auth/choices/None/description": "No authentication", + "symbols/auth/choices/Individual/description": "Individual authentication", + "symbols/auth/description": "The type of authentication to use", + "symbols/UseLocalDB/description": "Whether to use LocalDB instead of SQLite. This option only applies if --auth Individual is specified.", "symbols/AllInteractive/displayName": "_Enable interactive rendering globally throughout the site", "symbols/AllInteractive/description": "Configures whether to make every page interactive by applying an interactive render mode at the top level. If false, pages will use static server rendering by default, and can be marked interactive on a per-page or per-component basis.", "symbols/NoHttps/description": "Ob HTTPS deaktiviert werden soll. Diese Option gilt nur, wenn Individual, IndividualB2C, SingleOrg oder MultiOrg nicht für --auth verwendet werden.", diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.en.json b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.en.json index 60d16e15ffd9..6db424a9f348 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.en.json +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.en.json @@ -4,12 +4,13 @@ "description": "A project template for creating a Blazor web app that supports both server-side rendering and client interactivity. This template can be used for web apps with rich dynamic user interfaces (UIs).", "symbols/Framework/description": "The target framework for the project.", "symbols/Framework/choices/net8.0/description": "Target net8.0", + "symbols/UserSecretsId/description": "The ID to use for secrets (use with Individual auth).", "symbols/skipRestore/description": "If specified, skips the automatic restore of the project on create.", "symbols/ExcludeLaunchSettings/description": "Whether to exclude launchSettings.json from the generated template.", "symbols/kestrelHttpPort/description": "Port number to use for the HTTP endpoint in launchSettings.json.", - "symbols/kestrelHttpsPort/description": "Port number to use for the HTTPS endpoint in launchSettings.json. This option is only applicable when the parameter no-https is not used (no-https will be ignored if either IndividualAuth or OrganizationalAuth is used).", + "symbols/kestrelHttpsPort/description": "Port number to use for the HTTPS endpoint in launchSettings.json. This option is only applicable when the parameter no-https is not used (no-https will be ignored if Individual auth is used).", "symbols/iisHttpPort/description": "Port number to use for the IIS Express HTTP endpoint in launchSettings.json.", - "symbols/iisHttpsPort/description": "Port number to use for the IIS Express HTTPS endpoint in launchSettings.json. This option is only applicable when the parameter no-https is not used (no-https will be ignored if either IndividualAuth or OrganizationalAuth is used).", + "symbols/iisHttpsPort/description": "Port number to use for the IIS Express HTTPS endpoint in launchSettings.json. This option is only applicable when the parameter no-https is not used (no-https will be ignored if Individual auth is used).", "symbols/InteractivityPlatform/displayName": "_Interactivity type", "symbols/InteractivityPlatform/description": "Chooses which hosting platform to use for interactive components", "symbols/InteractivityPlatform/choices/None/displayName": "None", @@ -29,9 +30,13 @@ "symbols/IncludeSampleContent/displayName": "_Include sample pages", "symbols/IncludeSampleContent/description": "Configures whether to add sample pages and styling to demonstrate basic usage patterns.", "symbols/Empty/description": "Configures whether to omit sample pages and styling that demonstrate basic usage patterns.", + "symbols/auth/choices/None/description": "No authentication", + "symbols/auth/choices/Individual/description": "Individual authentication", + "symbols/auth/description": "The type of authentication to use", + "symbols/UseLocalDB/description": "Whether to use LocalDB instead of SQLite. This option only applies if --auth Individual is specified.", "symbols/AllInteractive/displayName": "_Enable interactive rendering globally throughout the site", "symbols/AllInteractive/description": "Configures whether to make every page interactive by applying an interactive render mode at the top level. If false, pages will use static server rendering by default, and can be marked interactive on a per-page or per-component basis.", - "symbols/NoHttps/description": "Whether to turn off HTTPS. This option only applies if Individual, IndividualB2C, SingleOrg, or MultiOrg aren't used for --auth.", + "symbols/NoHttps/description": "Whether to turn off HTTPS. This option only applies if Individual isn't used for --auth.", "symbols/UseProgramMain/displayName": "Do not use _top-level statements", "symbols/UseProgramMain/description": "Whether to generate an explicit Program class and Main method instead of top-level statements.", "postActions/restore/description": "Restore NuGet packages required by this project.", diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.es.json b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.es.json index 91d5403e0fbf..ddb3601195d3 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.es.json +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.es.json @@ -4,6 +4,7 @@ "description": "Plantilla de proyecto para crear una aplicación web de Blazor que admita tanto la representación del lado del servidor como la interactividad del cliente. Esta plantilla se puede usar para las aplicaciones web con interfaces de usuario dinámicas enriquecidas.", "symbols/Framework/description": "Marco de destino del proyecto.", "symbols/Framework/choices/net8.0/description": "net8.0 de destino", + "symbols/UserSecretsId/description": "The ID to use for secrets (use with Individual auth).", "symbols/skipRestore/description": "Si se especifica, se omite la restauración automática del proyecto durante la creación.", "symbols/ExcludeLaunchSettings/description": "Indica si se va a excluir launchSettings.json de la plantilla generada.", "symbols/kestrelHttpPort/description": "Número de puerto que se va a usar para el punto de conexión HTTP en launchSettings.json.", @@ -29,6 +30,10 @@ "symbols/IncludeSampleContent/displayName": "_Incluir páginas de ejemplo", "symbols/IncludeSampleContent/description": "Configura si se van a agregar páginas de ejemplo y estilos para mostrar patrones de uso básicos.", "symbols/Empty/description": "Configura si se omiten las páginas de ejemplo y los estilos que muestran patrones de uso básicos.", + "symbols/auth/choices/None/description": "No authentication", + "symbols/auth/choices/Individual/description": "Individual authentication", + "symbols/auth/description": "The type of authentication to use", + "symbols/UseLocalDB/description": "Whether to use LocalDB instead of SQLite. This option only applies if --auth Individual is specified.", "symbols/AllInteractive/displayName": "_Enable interactive rendering globally throughout the site", "symbols/AllInteractive/description": "Configures whether to make every page interactive by applying an interactive render mode at the top level. If false, pages will use static server rendering by default, and can be marked interactive on a per-page or per-component basis.", "symbols/NoHttps/description": "Si se va a desactivar HTTPS. Esta opción solo se aplica si Individual, IndividualB2C, SingleOrg o MultiOrg no se usan para --auth.", diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.fr.json b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.fr.json index 044f40bacc91..b902e5a58b87 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.fr.json +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.fr.json @@ -4,6 +4,7 @@ "description": "Modèle de projet pour la création d’une application web Blazor qui prend en charge le rendu côté serveur et l’interactivité du client. Ce modèle peut être utilisé pour les applications web avec des interfaces utilisateur dynamiques enrichies.", "symbols/Framework/description": "Framework cible du projet.", "symbols/Framework/choices/net8.0/description": "Cible net8.0", + "symbols/UserSecretsId/description": "The ID to use for secrets (use with Individual auth).", "symbols/skipRestore/description": "S’il est spécifié, ignore la restauration automatique du projet lors de la création.", "symbols/ExcludeLaunchSettings/description": "Indique s’il faut exclure launchSettings.json du modèle généré.", "symbols/kestrelHttpPort/description": "Numéro de port à utiliser pour le point de terminaison HTTP dans launchSettings.json.", @@ -29,6 +30,10 @@ "symbols/IncludeSampleContent/displayName": "_Inclure des exemples de pages", "symbols/IncludeSampleContent/description": "Configure s'il faut ajouter des exemples de pages et de style pour illustrer les modèles d'utilisation de base.", "symbols/Empty/description": "Configure s'il faut omettre les exemples de pages et le style qui illustrent les modèles d'utilisation de base.", + "symbols/auth/choices/None/description": "No authentication", + "symbols/auth/choices/Individual/description": "Individual authentication", + "symbols/auth/description": "The type of authentication to use", + "symbols/UseLocalDB/description": "Whether to use LocalDB instead of SQLite. This option only applies if --auth Individual is specified.", "symbols/AllInteractive/displayName": "_Enable interactive rendering globally throughout the site", "symbols/AllInteractive/description": "Configures whether to make every page interactive by applying an interactive render mode at the top level. If false, pages will use static server rendering by default, and can be marked interactive on a per-page or per-component basis.", "symbols/NoHttps/description": "Indique s’il faut désactiver HTTPS. Cette option s’applique uniquement si Individual, IndividualB2C, SingleOrg ou MultiOrg ne sont pas utilisés pour --auth.", diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.it.json b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.it.json index 09c3ebfff2c2..14edbef4335b 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.it.json +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.it.json @@ -4,6 +4,7 @@ "description": "Modello di progetto per la creazione di un'app Web Blazor che supporta sia il rendering lato server sia l'interattività client. Questo modello può essere usato per app Web con interfacce utente dinamiche avanzate.", "symbols/Framework/description": "Il framework di destinazione per il progetto.", "symbols/Framework/choices/net8.0/description": "Destinazione net8.0", + "symbols/UserSecretsId/description": "The ID to use for secrets (use with Individual auth).", "symbols/skipRestore/description": "Se specificato, ignora il ripristino automatico del progetto durante la creazione.", "symbols/ExcludeLaunchSettings/description": "Indica se escludere launchSettings.json dal modello generato.", "symbols/kestrelHttpPort/description": "Numero di porta da usare per l'endpoint HTTP in launchSettings.json.", @@ -29,6 +30,10 @@ "symbols/IncludeSampleContent/displayName": "_Include pagine di esempio", "symbols/IncludeSampleContent/description": "Consente di configurare se aggiungere pagine di esempio e stile per mostrare modelli di utilizzo di base.", "symbols/Empty/description": "Consente di configurare se omettere pagine di esempio e stile che mostrano modelli di utilizzo di base.", + "symbols/auth/choices/None/description": "No authentication", + "symbols/auth/choices/Individual/description": "Individual authentication", + "symbols/auth/description": "The type of authentication to use", + "symbols/UseLocalDB/description": "Whether to use LocalDB instead of SQLite. This option only applies if --auth Individual is specified.", "symbols/AllInteractive/displayName": "_Enable interactive rendering globally throughout the site", "symbols/AllInteractive/description": "Configures whether to make every page interactive by applying an interactive render mode at the top level. If false, pages will use static server rendering by default, and can be marked interactive on a per-page or per-component basis.", "symbols/NoHttps/description": "Indica se disattivare HTTPS. Questa opzione si applica solo se Individual, IndividualB2C, SingleOrg o MultiOrg non vengono usati per --auth.", diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.ja.json b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.ja.json index f48aecfb9534..2b7fabb722e0 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.ja.json +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.ja.json @@ -4,6 +4,7 @@ "description": "サーバー側のレンダリングとクライアントの対話機能の両方をサポートする Blazor Web アプリを作成するためのプロジェクト テンプレートです。このテンプレートは、リッチな動的ユーザー インターフェイス (UI) を持つ Web アプリに使用できます。", "symbols/Framework/description": "プロジェクトのターゲット フレームワークです。", "symbols/Framework/choices/net8.0/description": "ターゲット net8.0", + "symbols/UserSecretsId/description": "The ID to use for secrets (use with Individual auth).", "symbols/skipRestore/description": "指定した場合、作成時にプロジェクトの自動復元がスキップされます。", "symbols/ExcludeLaunchSettings/description": "生成されたテンプレートから launchSettings.json を除外するかどうか。", "symbols/kestrelHttpPort/description": "launchSettings.json の HTTP エンドポイントに使用するポート番号。", @@ -29,6 +30,10 @@ "symbols/IncludeSampleContent/displayName": "サンプル ページを含める(_I)", "symbols/IncludeSampleContent/description": "基本的な使用パターンを示すサンプル ページとスタイルを追加するかどうかを構成します。", "symbols/Empty/description": "基本的な使用パターンを示すサンプル ページとスタイルを省略するかどうかを構成します。", + "symbols/auth/choices/None/description": "No authentication", + "symbols/auth/choices/Individual/description": "Individual authentication", + "symbols/auth/description": "The type of authentication to use", + "symbols/UseLocalDB/description": "Whether to use LocalDB instead of SQLite. This option only applies if --auth Individual is specified.", "symbols/AllInteractive/displayName": "_Enable interactive rendering globally throughout the site", "symbols/AllInteractive/description": "Configures whether to make every page interactive by applying an interactive render mode at the top level. If false, pages will use static server rendering by default, and can be marked interactive on a per-page or per-component basis.", "symbols/NoHttps/description": "HTTPS をオフにするかどうか。このオプションは、Individual、IndividualB2C、SingleOrg、または MultiOrg が --auth に使用されていない場合にのみ適用されます。", diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.ko.json b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.ko.json index 020ab522da02..f0319af43653 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.ko.json +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.ko.json @@ -4,6 +4,7 @@ "description": "서버 측 렌더링 및 클라이언트 대화형 작업을 모두 지원하는 Blazor 웹앱을 만들기 위한 프로젝트 템플릿입니다. 이 템플릿은 풍부한 동적 UI(사용자 인터페이스)가 있는 웹앱에 사용할 수 있습니다.", "symbols/Framework/description": "프로젝트에 대한 대상 프레임워크입니다.", "symbols/Framework/choices/net8.0/description": "대상 net8.0", + "symbols/UserSecretsId/description": "The ID to use for secrets (use with Individual auth).", "symbols/skipRestore/description": "지정된 경우, 프로젝트 생성 시 자동 복원을 건너뜁니다.", "symbols/ExcludeLaunchSettings/description": "생성된 템플릿에서 launchSettings.json을 제외할지 여부입니다.", "symbols/kestrelHttpPort/description": "launchSettings.json의 HTTP 엔드포인트에 사용할 포트 번호입니다.", @@ -29,6 +30,10 @@ "symbols/IncludeSampleContent/displayName": "샘플 페이지 포함(_I)", "symbols/IncludeSampleContent/description": "기본 사용 패턴을 보여주기 위해 샘플 페이지 및 스타일을 추가할지 여부를 구성합니다.", "symbols/Empty/description": "기본 사용 패턴을 보여주는 샘플 페이지 및 스타일을 생략할지 여부를 구성합니다.", + "symbols/auth/choices/None/description": "No authentication", + "symbols/auth/choices/Individual/description": "Individual authentication", + "symbols/auth/description": "The type of authentication to use", + "symbols/UseLocalDB/description": "Whether to use LocalDB instead of SQLite. This option only applies if --auth Individual is specified.", "symbols/AllInteractive/displayName": "_Enable interactive rendering globally throughout the site", "symbols/AllInteractive/description": "Configures whether to make every page interactive by applying an interactive render mode at the top level. If false, pages will use static server rendering by default, and can be marked interactive on a per-page or per-component basis.", "symbols/NoHttps/description": "HTTPS를 끌지 여부입니다. 이 옵션은 Individual, IndividualB2C, SingleOrg 또는 MultiOrg가 --auth에 사용되지 않는 경우에만 적용됩니다.", diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.pl.json b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.pl.json index 43e2693e0f62..aaa04bb545d6 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.pl.json +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.pl.json @@ -4,6 +4,7 @@ "description": "Szablon projektu służący do tworzenia aplikacji internetowej platformy Blazor, która obsługuje renderowanie po stronie serwera i interakcyjność klienta. Ten szablon może być używany dla aplikacji internetowych z zaawansowanymi dynamicznymi interfejsami użytkownika.", "symbols/Framework/description": "Platforma docelowa dla tego projektu.", "symbols/Framework/choices/net8.0/description": "Docelowa platforma net8.0", + "symbols/UserSecretsId/description": "The ID to use for secrets (use with Individual auth).", "symbols/skipRestore/description": "Jeśli ta opcja jest określona, pomija automatyczne przywracanie projektu podczas tworzenia.", "symbols/ExcludeLaunchSettings/description": "Określa, czy wykluczyć plik launchSettings.json z wygenerowanego szablonu.", "symbols/kestrelHttpPort/description": "Numer portu do użycia dla punktu końcowego HTTP w pliku launchSettings.json.", @@ -29,6 +30,10 @@ "symbols/IncludeSampleContent/displayName": "_Dołącz przykładowe strony", "symbols/IncludeSampleContent/description": "Konfiguruje, czy dodać przykładowe strony i style w celu zademonstrowania podstawowych wzorców użycia.", "symbols/Empty/description": "Konfiguruje, czy pomijać przykładowe strony i style demonstrujące podstawowe wzorce użycia.", + "symbols/auth/choices/None/description": "No authentication", + "symbols/auth/choices/Individual/description": "Individual authentication", + "symbols/auth/description": "The type of authentication to use", + "symbols/UseLocalDB/description": "Whether to use LocalDB instead of SQLite. This option only applies if --auth Individual is specified.", "symbols/AllInteractive/displayName": "_Enable interactive rendering globally throughout the site", "symbols/AllInteractive/description": "Configures whether to make every page interactive by applying an interactive render mode at the top level. If false, pages will use static server rendering by default, and can be marked interactive on a per-page or per-component basis.", "symbols/NoHttps/description": "Określa, czy wyłączyć protokół HTTPS. Ta opcja ma zastosowanie tylko wtedy, gdy dla uwierzytelniania --auth nie są używane elementy Individual, IndividualB2C, SingleOrg lub MultiOrg.", diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.pt-BR.json b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.pt-BR.json index dc3922339c3b..b0969274dcc2 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.pt-BR.json +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.pt-BR.json @@ -4,6 +4,7 @@ "description": "Um modelo de projeto para criar um aplicativo Web Blazor que dá suporte à renderização do lado do servidor e à interatividade do cliente. Este modelo pode ser usado para aplicativos da Web com interfaces de usuário (UIs) dinâmicas avançadas.", "symbols/Framework/description": "A estrutura de destino do projeto.", "symbols/Framework/choices/net8.0/description": "net8.0 de destino", + "symbols/UserSecretsId/description": "The ID to use for secrets (use with Individual auth).", "symbols/skipRestore/description": "Se especificado, ignora a restauração automática do projeto sendo criado.", "symbols/ExcludeLaunchSettings/description": "Se deve excluir launchSettings.json do modelo gerado.", "symbols/kestrelHttpPort/description": "Número da porta a ser usada para o ponto de extremidade HTTP em launchSettings.json.", @@ -29,6 +30,10 @@ "symbols/IncludeSampleContent/displayName": "_Incluir páginas de amostra", "symbols/IncludeSampleContent/description": "Configura se deseja adicionar páginas de amostra e estilo para demonstrar padrões de uso básicos.", "symbols/Empty/description": "Configura a omissão de páginas de amostra e estilo que demonstram padrões básicos de uso.", + "symbols/auth/choices/None/description": "No authentication", + "symbols/auth/choices/Individual/description": "Individual authentication", + "symbols/auth/description": "The type of authentication to use", + "symbols/UseLocalDB/description": "Whether to use LocalDB instead of SQLite. This option only applies if --auth Individual is specified.", "symbols/AllInteractive/displayName": "_Enable interactive rendering globally throughout the site", "symbols/AllInteractive/description": "Configures whether to make every page interactive by applying an interactive render mode at the top level. If false, pages will use static server rendering by default, and can be marked interactive on a per-page or per-component basis.", "symbols/NoHttps/description": "Se o HTTPS deve ser desativado. Essa opção se aplica somente se Individual, IndividualB2C, SingleOrg ou MultiOrg não forem usados para --auth.", diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.ru.json b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.ru.json index f9d64e65d85a..eea4080639dc 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.ru.json +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.ru.json @@ -4,6 +4,7 @@ "description": "Шаблон проекта для создания приложения Blazor, поддерживающего как отрисовку на стороне сервера, так и интерактивные возможности клиента. Этот шаблон можно использовать для веб-приложений с многофункциональными динамическими пользовательскими интерфейсами (UI).", "symbols/Framework/description": "Целевая платформа для проекта.", "symbols/Framework/choices/net8.0/description": "Целевая net8.0", + "symbols/UserSecretsId/description": "The ID to use for secrets (use with Individual auth).", "symbols/skipRestore/description": "Если установлено, автоматическое восстановление проекта при создании пропускается.", "symbols/ExcludeLaunchSettings/description": "Следует ли исключить launchSettings.json из созданного шаблона.", "symbols/kestrelHttpPort/description": "Номер порта, используемый для конечной точки HTTP в launchSettings.json.", @@ -29,6 +30,10 @@ "symbols/IncludeSampleContent/displayName": "_Включить примеры страниц", "symbols/IncludeSampleContent/description": "Настраивает, следует ли добавлять примеры страниц и стили для демонстрации базовых шаблонов использования.", "symbols/Empty/description": "Настраивает, следует ли пропускать примеры страниц и стили, демонстрирующие базовые шаблоны использования.", + "symbols/auth/choices/None/description": "No authentication", + "symbols/auth/choices/Individual/description": "Individual authentication", + "symbols/auth/description": "The type of authentication to use", + "symbols/UseLocalDB/description": "Whether to use LocalDB instead of SQLite. This option only applies if --auth Individual is specified.", "symbols/AllInteractive/displayName": "_Enable interactive rendering globally throughout the site", "symbols/AllInteractive/description": "Configures whether to make every page interactive by applying an interactive render mode at the top level. If false, pages will use static server rendering by default, and can be marked interactive on a per-page or per-component basis.", "symbols/NoHttps/description": "Следует ли отключить HTTPS. Этот параметр применяется, только если для --auth не используются Individual, IndividualB2C, SingleOrg или MultiOrg.", diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.tr.json b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.tr.json index 5299f026392a..ae3be7fb7b06 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.tr.json +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.tr.json @@ -4,6 +4,7 @@ "description": "Hem sunucu tarafı işlemeyi hem de istemci etkileşimini destekleyen bir Blazor web uygulaması oluşturmaya yönelik proje şablonu. Bu şablon, zengin dinamik kullanıcı arabirimlerine (UI) sahip web uygulamaları için kullanılabilir.", "symbols/Framework/description": "Projenin hedef çerçevesi.", "symbols/Framework/choices/net8.0/description": "Hedef net8.0", + "symbols/UserSecretsId/description": "The ID to use for secrets (use with Individual auth).", "symbols/skipRestore/description": "Belirtilirse, oluşturma sırasında projenin otomatik geri yüklenmesini atlar.", "symbols/ExcludeLaunchSettings/description": "launchSettings.json öğesinin oluşturulan şablondan dışlanıp dışlanmayacağı.", "symbols/kestrelHttpPort/description": "launchSettings.json içinde HTTP uç noktası için kullanılacak bağlantı noktası numarası.", @@ -29,6 +30,10 @@ "symbols/IncludeSampleContent/displayName": "Örnek _sayfalar ekle", "symbols/IncludeSampleContent/description": "Temel kullanım düzenlerini göstermek için örnek sayfaların ve stil oluşturma özelliklerinin eklenip eklenmeyeceğini yapılandırır.", "symbols/Empty/description": "Temel kullanım düzenlerini gösteren örnek sayfaların ve stil oluşturma özelliklerinin atlanıp atlanmayacağını yapılandırır.", + "symbols/auth/choices/None/description": "No authentication", + "symbols/auth/choices/Individual/description": "Individual authentication", + "symbols/auth/description": "The type of authentication to use", + "symbols/UseLocalDB/description": "Whether to use LocalDB instead of SQLite. This option only applies if --auth Individual is specified.", "symbols/AllInteractive/displayName": "_Enable interactive rendering globally throughout the site", "symbols/AllInteractive/description": "Configures whether to make every page interactive by applying an interactive render mode at the top level. If false, pages will use static server rendering by default, and can be marked interactive on a per-page or per-component basis.", "symbols/NoHttps/description": "HTTPS'nin kapatılıp kapatılmayacağı. Bu seçenek yalnızca Bireysel, IndividualB2C, SingleOrg veya MultiOrg -- auth için kullanılmazsa geçerlidir.", diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.zh-Hans.json b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.zh-Hans.json index 27bbe0d23ea5..b17c3da9b57a 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.zh-Hans.json +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.zh-Hans.json @@ -4,6 +4,7 @@ "description": "用于创建支持服务器端呈现和客户端交互的 Blazor Web 应用的项目模板。此模板可用于具有丰富动态用户界面 (UI) 的 Web 应用。", "symbols/Framework/description": "项目的目标框架。", "symbols/Framework/choices/net8.0/description": "目标 net8.0", + "symbols/UserSecretsId/description": "The ID to use for secrets (use with Individual auth).", "symbols/skipRestore/description": "如果指定,则在创建时跳过项目的自动还原。", "symbols/ExcludeLaunchSettings/description": "是否从生成的模板中排除 launchSettings.json。", "symbols/kestrelHttpPort/description": "要用于 launchSettings.json 中 HTTP 终结点的端口号。", @@ -29,6 +30,10 @@ "symbols/IncludeSampleContent/displayName": "包含示例页(_I)", "symbols/IncludeSampleContent/description": "配置是否添加示例页和样式以演示基本使用模式。", "symbols/Empty/description": "配置是否忽略演示基本使用模式的示例页和样式。", + "symbols/auth/choices/None/description": "No authentication", + "symbols/auth/choices/Individual/description": "Individual authentication", + "symbols/auth/description": "The type of authentication to use", + "symbols/UseLocalDB/description": "Whether to use LocalDB instead of SQLite. This option only applies if --auth Individual is specified.", "symbols/AllInteractive/displayName": "_Enable interactive rendering globally throughout the site", "symbols/AllInteractive/description": "Configures whether to make every page interactive by applying an interactive render mode at the top level. If false, pages will use static server rendering by default, and can be marked interactive on a per-page or per-component basis.", "symbols/NoHttps/description": "是否禁用 HTTPS。仅当 Individual、IndividualB2C、SingleOrg 或 MultiOrg 不用于 --auth 时,此选项才适用。", diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.zh-Hant.json b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.zh-Hant.json index f1c7a0d88ba7..5155a158b99b 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.zh-Hant.json +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/localize/templatestrings.zh-Hant.json @@ -4,6 +4,7 @@ "description": "用於建立同時支援伺服器端轉譯和用戶端互動的 Blazor Web 應用程式的專案範本。此範本可用於具有豐富動態使用者介面 (UI) 的 Web 應用程式。", "symbols/Framework/description": "專案的目標 Framework。", "symbols/Framework/choices/net8.0/description": "目標 net8.0", + "symbols/UserSecretsId/description": "The ID to use for secrets (use with Individual auth).", "symbols/skipRestore/description": "若指定,會在建立時跳過專案的自動還原。", "symbols/ExcludeLaunchSettings/description": "是否要從產生的範本排除 launchSettings.json。", "symbols/kestrelHttpPort/description": "launchSettings.json 中 HTTP 端點要使用的連接埠號碼。", @@ -29,6 +30,10 @@ "symbols/IncludeSampleContent/displayName": "包含範例頁面(_I)", "symbols/IncludeSampleContent/description": "設定是否要新增範例頁面和樣式,以示範基本使用模式。", "symbols/Empty/description": "設定是否要省略範例頁面和樣式,其示範基本使用模式。", + "symbols/auth/choices/None/description": "No authentication", + "symbols/auth/choices/Individual/description": "Individual authentication", + "symbols/auth/description": "The type of authentication to use", + "symbols/UseLocalDB/description": "Whether to use LocalDB instead of SQLite. This option only applies if --auth Individual is specified.", "symbols/AllInteractive/displayName": "_Enable interactive rendering globally throughout the site", "symbols/AllInteractive/description": "Configures whether to make every page interactive by applying an interactive render mode at the top level. If false, pages will use static server rendering by default, and can be marked interactive on a per-page or per-component basis.", "symbols/NoHttps/description": "是否要關閉 HTTPS。只有當 Individual、IndividualB2C、SingleOrg 或 MultiOrg 未用於 --auth 時,才適用此選項。", diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/template.json b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/template.json index 971eb62028ba..9356b1e5a7a1 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/template.json +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/.template.config/template.json @@ -14,7 +14,8 @@ "guids": [ "4C26868E-5E7C-458D-82E3-040509D0C71F", "5990939C-7E7B-4CFA-86FF-44CA5756498A", - "650B3CE7-2E93-4CC4-9F46-466686815EAA" + "650B3CE7-2E93-4CC4-9F46-466686815EAA", + "53bc9b9d-9d6a-45d4-8429-2a2761773502" ], "identity": "Microsoft.Web.Blazor.CSharp.8.0", "thirdPartyNotices": "https://aka.ms/aspnetcore/8.0-third-party-notices", @@ -108,6 +109,86 @@ "BlazorWeb-CSharp.Client/Pages/**", "BlazorWeb-CSharp.Client/wwwroot/**" ] + }, + { + "condition": "(!IndividualLocalAuth)", + "exclude": [ + "BlazorWeb-CSharp/Components/Identity/**", + "BlazorWeb-CSharp/Components/Layout/ManageLayout.razor", + "BlazorWeb-CSharp/Components/Layout/ManageNavMenu.razor", + "BlazorWeb-CSharp/Components/Pages/Account/**", + "BlazorWeb-CSharp/Data/**", + "BlazorWeb-CSharp/Identity/**", + "BlazorWeb-CSharp.Client/PersistentAuthenticationStateProvider.cs", + "BlazorWeb-CSharp.Client/UserInfo.cs", + "BlazorWeb-CSharp.Client/Pages/Auth.razor" + ] + }, + { + "condition": "(!(IndividualLocalAuth && !UseLocalDB))", + "exclude": [ + "BlazorWeb-CSharp/app.db" + ] + }, + { + "condition": "(!(IndividualLocalAuth && !UseWebAssembly))", + "exclude": [ + "BlazorWeb-CSharp/Components/Pages/Auth.razor" + ] + }, + { + "condition": "(!(IndividualLocalAuth && UseServer && UseWebAssembly))", + "exclude": [ + "BlazorWeb-CSharp/Identity/PersistingRevalidatingAuthenticationStateProvider.cs" + ] + }, + { + "condition": "(!(IndividualLocalAuth && UseServer && !UseWebAssembly))", + "exclude": [ + "BlazorWeb-CSharp/Identity/IdentityRevalidatingAuthenticationStateProvider.cs" + ] + }, + { + "condition": "(!(IndividualLocalAuth && !UseServer && UseWebAssembly))", + "exclude": [ + "BlazorWeb-CSharp/Identity/PersistingServerAuthenticationStateProvider.cs" + ] + }, + { + "condition": "(IndividualLocalAuth && UseLocalDB && UseWebAssembly)", + "rename": { + "BlazorWeb-CSharp/Data/SqlServer/": "BlazorWeb-CSharp/Data/Migrations/" + }, + "exclude": [ + "BlazorWeb-CSharp/Data/SqlLite/**" + ] + }, + { + "condition": "(IndividualLocalAuth && UseLocalDB && !UseWebAssembly)", + "rename": { + "BlazorWeb-CSharp/Data/SqlServer/": "Data/Migrations/" + }, + "exclude": [ + "BlazorWeb-CSharp/Data/SqlLite/**" + ] + }, + { + "condition": "(IndividualLocalAuth && !UseLocalDB && UseWebAssembly)", + "rename": { + "BlazorWeb-CSharp/Data/SqlLite/": "BlazorWeb-CSharp/Data/Migrations/" + }, + "exclude": [ + "BlazorWeb-CSharp/Data/SqlServer/**" + ] + }, + { + "condition": "(IndividualLocalAuth && !UseLocalDB && !UseWebAssembly)", + "rename": { + "BlazorWeb-CSharp/Data/SqlLite/": "Data/Migrations/" + }, + "exclude": [ + "BlazorWeb-CSharp/Data/SqlServer/**" + ] } ] } @@ -130,6 +211,13 @@ "type": "bind", "binding": "HostIdentifier" }, + "UserSecretsId": { + "type": "parameter", + "datatype": "string", + "replaces": "aspnet-BlazorWeb-CSharp-53bc9b9d-9d6a-45d4-8429-2a2761773502", + "defaultValue": "aspnet-BlazorWeb-CSharp-53bc9b9d-9d6a-45d4-8429-2a2761773502", + "description": "The ID to use for secrets (use with Individual auth)." + }, "skipRestore": { "type": "parameter", "datatype": "bool", @@ -167,7 +255,7 @@ "kestrelHttpsPort": { "type": "parameter", "datatype": "integer", - "description": "Port number to use for the HTTPS endpoint in launchSettings.json. This option is only applicable when the parameter no-https is not used (no-https will be ignored if either IndividualAuth or OrganizationalAuth is used)." + "description": "Port number to use for the HTTPS endpoint in launchSettings.json. This option is only applicable when the parameter no-https is not used (no-https will be ignored if Individual auth is used)." }, "kestrelHttpsPortGenerated": { "type": "generated", @@ -207,7 +295,7 @@ "iisHttpsPort": { "type": "parameter", "datatype": "integer", - "description": "Port number to use for the IIS Express HTTPS endpoint in launchSettings.json. This option is only applicable when the parameter no-https is not used (no-https will be ignored if either IndividualAuth or OrganizationalAuth is used)." + "description": "Port number to use for the IIS Express HTTPS endpoint in launchSettings.json. This option is only applicable when the parameter no-https is not used (no-https will be ignored if Individual auth is used)." }, "iisHttpsPortGenerated": { "type": "generated", @@ -261,7 +349,7 @@ "defaultValue": "InteractivePerPage", "displayName": "_Interactivity location", "description": "Chooses which components will have interactive rendering enabled", - "isEnabled": "(InteractivityPlatform != \"None\")", + "isEnabled": "(InteractivityPlatform != \"None\" && auth == \"None\")", "choices": [ { "choice": "InteractivePerPage", @@ -296,6 +384,28 @@ "defaultValue": "false", "description": "Configures whether to omit sample pages and styling that demonstrate basic usage patterns." }, + "auth": { + "type": "parameter", + "datatype": "choice", + "choices": [ + { + "choice": "None", + "description": "No authentication" + }, + { + "choice": "Individual", + "description": "Individual authentication" + } + ], + "defaultValue": "None", + "description": "The type of authentication to use" + }, + "UseLocalDB": { + "type": "parameter", + "datatype": "bool", + "defaultValue": "false", + "description": "Whether to use LocalDB instead of SQLite. This option only applies if --auth Individual is specified." + }, "SampleContent": { "type": "computed", "value": "(((IncludeSampleContent && (HostIdentifier != \"dotnetcli\" && HostIdentifier != \"dotnetcli-preview\"))) || ((!Empty && (HostIdentifier == \"dotnetcli\" || HostIdentifier == \"dotnetcli-preview\"))))" @@ -303,7 +413,7 @@ "AllInteractive": { "type": "parameter", "datatype": "bool", - "isEnabled": "(InteractivityPlatform != \"None\")", + "isEnabled": "(InteractivityPlatform != \"None\" && auth == \"None\")", "defaultValue": "false", "displayName": "_Enable interactive rendering globally throughout the site", "description": "Configures whether to make every page interactive by applying an interactive render mode at the top level. If false, pages will use static server rendering by default, and can be marked interactive on a per-page or per-component basis." @@ -312,9 +422,13 @@ "type": "computed", "value": "(InteractivityLocation == \"InteractiveGlobal\" || AllInteractive)" }, + "IndividualLocalAuth": { + "type": "computed", + "value": "(auth == \"Individual\")" + }, "RequiresHttps": { "type": "computed", - "value": "(OrganizationalAuth || IndividualAuth)" + "value": "(OrganizationalAuth || IndividualLocalAuth)" }, "HasHttpProfile": { "type": "computed", @@ -328,7 +442,7 @@ "type": "parameter", "datatype": "bool", "defaultValue": "false", - "description": "Whether to turn off HTTPS. This option only applies if Individual, IndividualB2C, SingleOrg, or MultiOrg aren't used for --auth." + "description": "Whether to turn off HTTPS. This option only applies if Individual isn't used for --auth." }, "copyrightYear": { "type": "generated", diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp.Client/Pages/Auth.razor b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp.Client/Pages/Auth.razor new file mode 100644 index 000000000000..ebeeeccea168 --- /dev/null +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp.Client/Pages/Auth.razor @@ -0,0 +1,18 @@ +@page "/auth" + +@using Microsoft.AspNetCore.Authorization + +@attribute [Authorize] +@*#if (UseServer && !InteractiveAtRoot) +@attribute [RenderModeInteractiveAuto] +##elseif (!InteractiveAtRoot) +@attribute [RenderModeInteractiveWebAssembly] +##endif*@ + +Auth + +

You are authenticated

+ + + Hello @context.User.Identity?.Name! + diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp.Client/PersistentAuthenticationStateProvider.cs b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp.Client/PersistentAuthenticationStateProvider.cs new file mode 100644 index 000000000000..4f8e698ea75d --- /dev/null +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp.Client/PersistentAuthenticationStateProvider.cs @@ -0,0 +1,29 @@ +using System.Security.Claims; +using Microsoft.AspNetCore.Components; +using Microsoft.AspNetCore.Components.Authorization; + +namespace BlazorWeb_CSharp.Client; + +public class PersistentAuthenticationStateProvider(PersistentComponentState persistentState) : AuthenticationStateProvider +{ + private static readonly Task _unauthenticatedTask = + Task.FromResult(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()))); + + public override Task GetAuthenticationStateAsync() + { + if (!persistentState.TryTakeFromJson(nameof(UserInfo), out var userInfo) || userInfo is null) + { + return _unauthenticatedTask; + } + + Claim[] claims = [ + new Claim(ClaimTypes.NameIdentifier, userInfo.UserId), + new Claim(ClaimTypes.Name, userInfo.Email), + new Claim(ClaimTypes.Email, userInfo.Email) ]; + + return Task.FromResult( + new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity(claims, + authenticationType: nameof(PersistentAuthenticationStateProvider))))); + } +} + diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp.Client/Program.cs b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp.Client/Program.cs index 519269f21bb8..600e37d36537 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp.Client/Program.cs +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp.Client/Program.cs @@ -1,5 +1,15 @@ +#if (IndividualLocalAuth) +using BlazorWeb_CSharp.Client; +using Microsoft.AspNetCore.Components.Authorization; +#endif using Microsoft.AspNetCore.Components.WebAssembly.Hosting; var builder = WebAssemblyHostBuilder.CreateDefault(args); +#if (IndividualLocalAuth) +builder.Services.AddAuthorizationCore(); +builder.Services.AddCascadingAuthenticationState(); +builder.Services.AddSingleton(); + +#endif await builder.Build().RunAsync(); diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp.Client/UserInfo.cs b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp.Client/UserInfo.cs new file mode 100644 index 000000000000..236bbaa720da --- /dev/null +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp.Client/UserInfo.cs @@ -0,0 +1,7 @@ +namespace BlazorWeb_CSharp.Client; + +public class UserInfo +{ + public required string UserId { get; set; } + public required string Email { get; set; } +} diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp.Client/_Imports.razor b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp.Client/_Imports.razor index 5268e26fd6aa..cd618a113368 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp.Client/_Imports.razor +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp.Client/_Imports.razor @@ -1,5 +1,8 @@ @using System.Net.Http @using System.Net.Http.Json +@*#if (IndividualLocalAuth) +@using Microsoft.AspNetCore.Components.Authorization +##endif*@ @using Microsoft.AspNetCore.Components.Forms @using Microsoft.AspNetCore.Components.Routing @using Microsoft.AspNetCore.Components.Web diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Identity/ExternalLoginPicker.razor b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Identity/ExternalLoginPicker.razor new file mode 100644 index 000000000000..5c33681f7021 --- /dev/null +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Identity/ExternalLoginPicker.razor @@ -0,0 +1,47 @@ +@using Microsoft.AspNetCore.Authentication +@using Microsoft.AspNetCore.Identity +@using BlazorWeb_CSharp.Components.Pages.Account +@using BlazorWeb_CSharp.Data +@using BlazorWeb_CSharp.Identity + +@inject SignInManager SignInManager +@inject IdentityRedirectManager RedirectManager + +@if ((_externalLogins?.Count ?? 0) == 0) +{ +
+

+ There are no external authentication services configured. See this article + about setting up this ASP.NET application to support logging in via external services. +

+
+} +else +{ +
+
+ + +

+ @foreach (var provider in _externalLogins!) + { + + } +

+
+
+} + +@code { + private IList? _externalLogins; + + [SupplyParameterFromQuery] + private string ReturnUrl { get; set; } = default!; + + protected override async Task OnInitializedAsync() + { + ReturnUrl ??= "/"; + + _externalLogins = (await SignInManager.GetExternalAuthenticationSchemesAsync()).ToList(); + } +} diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Identity/LogoutForm.razor b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Identity/LogoutForm.razor new file mode 100644 index 000000000000..a08c78fc4cdc --- /dev/null +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Identity/LogoutForm.razor @@ -0,0 +1,34 @@ +@using Microsoft.AspNetCore.Identity +@using BlazorWeb_CSharp.Data +@using BlazorWeb_CSharp.Identity + +@inject SignInManager SignInManager +@inject NavigationManager NavigationManager +@inject IdentityRedirectManager RedirectManager + +
+ + + + +@code { + [Parameter(CaptureUnmatchedValues = true)] + public IDictionary? AdditionalAttributes { get; set; } + + [SupplyParameterFromForm] + private string? ReturnUrl { get; set; } + + [CascadingParameter] + private HttpContext HttpContext { get; set; } = default!; + + private async Task OnSubmitAsync() + { + var user = HttpContext.User; + + if (SignInManager.IsSignedIn(user)) + { + await SignInManager.SignOutAsync(); + RedirectManager.RedirectTo(ReturnUrl ?? "/"); + } + } +} diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Identity/ShowRecoveryCodes.razor b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Identity/ShowRecoveryCodes.razor new file mode 100644 index 000000000000..cebec61aef19 --- /dev/null +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Identity/ShowRecoveryCodes.razor @@ -0,0 +1,32 @@ + +

Recovery codes

+ +
+
+ @for (var row = 0; row < RecoveryCodes.Length; row += 2) + { + @RecoveryCodes[row] + +   + + @RecoveryCodes[row + 1] + +
+ } +
+
+ +@code { + [Parameter] + public string[] RecoveryCodes { get; set; } = default!; + + [Parameter] + public string StatusMessage { get; set; } = default!; +} diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Identity/StatusMessage.razor b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Identity/StatusMessage.razor new file mode 100644 index 000000000000..43bcdc0478b6 --- /dev/null +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Identity/StatusMessage.razor @@ -0,0 +1,29 @@ +@using BlazorWeb_CSharp.Identity + +@{ + var message = Message ?? MessageFromCookie; + + if (MessageFromCookie is not null) + { + HttpContext.Response.Cookies.Delete(IdentityRedirectManager.StatusCookieName); + } +} + +@if (!string.IsNullOrEmpty(message)) +{ + var statusMessageClass = message.StartsWith("Error") ? "danger" : "success"; + +} + +@code { + [Parameter] + public string? Message { get; set; } + + [CascadingParameter] + private HttpContext HttpContext { get; set; } = default!; + + private string? MessageFromCookie => HttpContext.Request.Cookies[IdentityRedirectManager.StatusCookieName]; +} diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Layout/ManageLayout.razor b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Layout/ManageLayout.razor new file mode 100644 index 000000000000..e4a7871bbc75 --- /dev/null +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Layout/ManageLayout.razor @@ -0,0 +1,17 @@ +@inherits LayoutComponentBase +@layout MainLayout + +

Manage your account

+ +
+

Change your account settings

+
+
+
+ +
+
+ @Body +
+
+
diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Layout/ManageNavMenu.razor b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Layout/ManageNavMenu.razor new file mode 100644 index 000000000000..8ffd7cd0a41e --- /dev/null +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Layout/ManageNavMenu.razor @@ -0,0 +1,37 @@ +@using Microsoft.AspNetCore.Identity; +@using BlazorWeb_CSharp.Data; + +@inject SignInManager SignInManager; + + + +@code { + private bool _hasExternalLogins; + + protected override async Task OnInitializedAsync() + { + _hasExternalLogins = (await SignInManager.GetExternalAuthenticationSchemesAsync()).Any(); + } +} diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Layout/NavMenu.razor b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Layout/NavMenu.razor index 5b141a54826b..5b38b21d63a7 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Layout/NavMenu.razor +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Layout/NavMenu.razor @@ -1,4 +1,8 @@ - diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Layout/NavMenu.razor.css b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Layout/NavMenu.razor.css index 95fcc36e0baa..14bddcebe4cf 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Layout/NavMenu.razor.css +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Layout/NavMenu.razor.css @@ -46,6 +46,28 @@ background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='white' class='bi bi-list-nested' viewBox='0 0 16 16'%3E%3Cpath fill-rule='evenodd' d='M4.5 11.5A.5.5 0 0 1 5 11h10a.5.5 0 0 1 0 1H5a.5.5 0 0 1-.5-.5zm-2-4A.5.5 0 0 1 3 7h10a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5zm-2-4A.5.5 0 0 1 1 3h10a.5.5 0 0 1 0 1H1a.5.5 0 0 1-.5-.5z'/%3E%3C/svg%3E"); } +/*#if (IndividualLocalAuth)*/ +.bi-lock { + background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='white' class='bi bi-list-nested' viewBox='0 0 16 16'%3E%3Cpath d='M8 1a2 2 0 0 1 2 2v4H6V3a2 2 0 0 1 2-2zm3 6V3a3 3 0 0 0-6 0v4a2 2 0 0 0-2 2v5a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2zM5 8h6a1 1 0 0 1 1 1v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V9a1 1 0 0 1 1-1z'/%3E%3C/svg%3E"); +} + +.bi-person { + background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='white' class='bi bi-person' viewBox='0 0 16 16'%3E%3Cpath d='M8 8a3 3 0 1 0 0-6 3 3 0 0 0 0 6Zm2-3a2 2 0 1 1-4 0 2 2 0 0 1 4 0Zm4 8c0 1-1 1-1 1H3s-1 0-1-1 1-4 6-4 6 3 6 4Zm-1-.004c-.001-.246-.154-.986-.832-1.664C11.516 10.68 10.289 10 8 10c-2.29 0-3.516.68-4.168 1.332-.678.678-.83 1.418-.832 1.664h10Z'/%3E%3C/svg%3E"); +} + +.bi-person-badge { + background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='white' class='bi bi-person-badge' viewBox='0 0 16 16'%3E%3Cpath d='M6.5 2a.5.5 0 0 0 0 1h3a.5.5 0 0 0 0-1h-3zM11 8a3 3 0 1 1-6 0 3 3 0 0 1 6 0z'/%3E%3Cpath d='M4.5 0A2.5 2.5 0 0 0 2 2.5V14a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V2.5A2.5 2.5 0 0 0 11.5 0h-7zM3 2.5A1.5 1.5 0 0 1 4.5 1h7A1.5 1.5 0 0 1 13 2.5v10.795a4.2 4.2 0 0 0-.776-.492C11.392 12.387 10.063 12 8 12s-3.392.387-4.224.803a4.2 4.2 0 0 0-.776.492V2.5z'/%3E%3C/svg%3E"); +} + +.bi-person-fill { + background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='white' class='bi bi-person-fill' viewBox='0 0 16 16'%3E%3Cpath d='M3 14s-1 0-1-1 1-4 6-4 6 3 6 4-1 1-1 1H3Zm5-6a3 3 0 1 0 0-6 3 3 0 0 0 0 6Z'/%3E%3C/svg%3E"); +} + +.bi-arrow-bar-left { + background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='white' class='bi bi-arrow-bar-left' viewBox='0 0 16 16'%3E%3Cpath d='M12.5 15a.5.5 0 0 1-.5-.5v-13a.5.5 0 0 1 1 0v13a.5.5 0 0 1-.5.5ZM10 8a.5.5 0 0 1-.5.5H3.707l2.147 2.146a.5.5 0 0 1-.708.708l-3-3a.5.5 0 0 1 0-.708l3-3a.5.5 0 1 1 .708.708L3.707 7.5H9.5a.5.5 0 0 1 .5.5Z'/%3E%3C/svg%3E"); +} + +/*#endif*/ .nav-item { font-size: 0.9rem; padding-bottom: 0.5rem; diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/ConfirmEmail.razor b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/ConfirmEmail.razor new file mode 100644 index 000000000000..992c6c59694f --- /dev/null +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/ConfirmEmail.razor @@ -0,0 +1,49 @@ +@page "/Account/ConfirmEmail" + +@using System.Text +@using Microsoft.AspNetCore.Identity +@using Microsoft.AspNetCore.WebUtilities +@using BlazorWeb_CSharp.Data +@using BlazorWeb_CSharp.Identity + +@inject UserManager UserManager +@inject IdentityRedirectManager RedirectManager + +Confirm email + +

Confirm email

+ + +@code { + string? statusMessage; + + [SupplyParameterFromQuery] + public string? UserId { get; set; } + + [SupplyParameterFromQuery] + public string? Code { get; set; } + + protected override async Task OnInitializedAsync() + { + if (UserId == null || Code == null) + { + RedirectManager.RedirectTo("/"); + } + else + { + var user = await UserManager.FindByIdAsync(UserId); + if (user == null) + { + // Need a way to trigger a 404 from Blazor: https://github.com/dotnet/aspnetcore/issues/45654 + statusMessage = $"Error loading user with ID {UserId}"; + } + else + { + + var code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(Code)); + var result = await UserManager.ConfirmEmailAsync(user, code); + statusMessage = result.Succeeded ? "Thank you for confirming your email." : "Error confirming your email."; + } + } + } +} \ No newline at end of file diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/ConfirmEmailChange.razor b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/ConfirmEmailChange.razor new file mode 100644 index 000000000000..510fb2d0e93f --- /dev/null +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/ConfirmEmailChange.razor @@ -0,0 +1,64 @@ +@page "/Account/ConfirmEmailChange" + +@using System.Text +@using Microsoft.AspNetCore.Identity +@using Microsoft.AspNetCore.WebUtilities +@using BlazorWeb_CSharp.Data +@using BlazorWeb_CSharp.Identity + +@inject UserManager UserManager +@inject SignInManager SignInManager +@inject UserAccessor UserAccessor +@inject IdentityRedirectManager RedirectManager + +Confirm email change + +

Confirm email change

+ + + +@code { + private string? _message; + private ApplicationUser _user = default!; + + [SupplyParameterFromQuery] + private string? UserId { get; set; } + + [SupplyParameterFromQuery] + private string? Email { get; set; } + + [SupplyParameterFromQuery] + private string? Code { get; set; } + + protected override async Task OnInitializedAsync() + { + if (UserId is null || Email is null || Code is null) + { + RedirectManager.RedirectToWithStatus( + "/Account/Login", "Error: Invalid email change confirmation link."); + return; + } + + _user = await UserAccessor.GetRequiredUserAsync(); + + var code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(Code)); + var result = await UserManager.ChangeEmailAsync(_user, Email, code); + if (!result.Succeeded) + { + _message = "Error changing email."; + return; + } + + // In our UI email and user name are one and the same, so when we update the email + // we need to update the user name. + var setUserNameResult = await UserManager.SetUserNameAsync(_user, Email); + if (!setUserNameResult.Succeeded) + { + _message = "Error changing user name."; + return; + } + + await SignInManager.RefreshSignInAsync(_user); + _message = "Thank you for confirming your email change."; + } +} diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/ExternalLogin.razor b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/ExternalLogin.razor new file mode 100644 index 000000000000..51bfa81fc116 --- /dev/null +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/ExternalLogin.razor @@ -0,0 +1,213 @@ +@page "/Account/ExternalLogin" + +@using System.ComponentModel.DataAnnotations +@using System.Security.Claims +@using System.Text +@using System.Text.Encodings.Web +@using Microsoft.AspNetCore.Identity +@using Microsoft.AspNetCore.Identity.UI.Services +@using Microsoft.AspNetCore.WebUtilities +@using BlazorWeb_CSharp.Data +@using BlazorWeb_CSharp.Identity + +@inject SignInManager SignInManager +@inject UserManager UserManager +@inject IUserStore UserStore +@inject IEmailSender EmailSender +@inject NavigationManager NavigationManager +@inject IdentityRedirectManager RedirectManager +@inject ILogger Logger + +@{ + var providerDisplayName = _externalLoginInfo.ProviderDisplayName; +} + +Register + + +

Register

+

Associate your @providerDisplayName account.

+
+ +
+ You've successfully authenticated with @providerDisplayName. + Please enter an email address for this site below and click the Register button to finish + logging in. +
+ +
+
+ + + +
+ + + +
+ +
+
+
+ +@code { + public const string LoginCallbackAction = "LoginCallback"; + + private string? _message; + private ExternalLoginInfo _externalLoginInfo = default!; + private IUserEmailStore _emailStore = default!; + + [SupplyParameterFromQuery] + private string? RemoteError { get; set; } + + [CascadingParameter] + public HttpContext HttpContext { get; set; } = default!; + + [SupplyParameterFromForm] + private InputModel Input { get; set; } = default!; + + [SupplyParameterFromQuery] + private string ReturnUrl { get; set; } = default!; + + [SupplyParameterFromQuery] + private string? Action { get; set; } = default!; + + protected override async Task OnInitializedAsync() + { + Input ??= new(); + ReturnUrl ??= "/"; + + if (RemoteError is not null) + { + RedirectManager.RedirectToWithStatus("/Account/Login", "Error from external provider: " + RemoteError); + return; + } + + var externalLoginInfo = await SignInManager.GetExternalLoginInfoAsync(); + if (externalLoginInfo is null) + { + RedirectManager.RedirectToWithStatus("/Account/Login", "Error loading external login information."); + return; + } + + _externalLoginInfo = externalLoginInfo; + _emailStore = GetEmailStore(); + + if (HttpMethods.IsGet(HttpContext.Request.Method)) + { + if (Action == LoginCallbackAction) + { + await OnLoginCallbackAsync(); + return; + } + + // We should only reach this page via the login callback, so redirect back to + // the login page if we get here some other way. + RedirectManager.RedirectTo("/Account/Login"); + return; + } + } + + private async Task OnLoginCallbackAsync() + { + // Sign in the user with this external login provider if the user already has a login. + var result = await SignInManager.ExternalLoginSignInAsync( + _externalLoginInfo.LoginProvider, + _externalLoginInfo.ProviderKey, + isPersistent: false, + bypassTwoFactor: true); + if (result.Succeeded) + { + Logger.LogInformation( + "{Name} logged in with {LoginProvider} provider.", + _externalLoginInfo.Principal.Identity?.Name, + _externalLoginInfo.LoginProvider); + RedirectManager.RedirectTo(ReturnUrl); + return; + } + + if (result.IsLockedOut) + { + RedirectManager.RedirectTo("/Account/Lockout"); + return; + } + + // If the user does not have an account, then ask the user to create an account. + if (_externalLoginInfo.Principal.HasClaim(c => c.Type == ClaimTypes.Email)) + { + Input.Email = _externalLoginInfo.Principal.FindFirstValue(ClaimTypes.Email); + } + } + + private async Task OnValidSubmitAsync() + { + var user = CreateUser(); + + await UserStore.SetUserNameAsync(user, Input.Email, CancellationToken.None); + await _emailStore.SetEmailAsync(user, Input.Email, CancellationToken.None); + + var result = await UserManager.CreateAsync(user); + if (result.Succeeded) + { + result = await UserManager.AddLoginAsync(user, _externalLoginInfo); + if (result.Succeeded) + { + Logger.LogInformation("User created an account using {Name} provider.", _externalLoginInfo.LoginProvider); + + var userId = await UserManager.GetUserIdAsync(user); + var code = await UserManager.GenerateEmailConfirmationTokenAsync(user); + code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); + + var callbackUrl = NavigationManager.GetUriWithQueryParameters( + $"{NavigationManager.BaseUri}Account/ConfirmEmail", + new Dictionary { { "userId", userId }, { "code", code } }); + await EmailSender.SendEmailAsync(Input.Email!, "Confirm your email", + $"Please confirm your account by clicking here."); + + // If account confirmation is required, we need to show the link if we don't have a real email sender + if (UserManager.Options.SignIn.RequireConfirmedAccount) + { + RedirectManager.RedirectTo("/Account/RegisterConfirmation", new() { ["Email"] = Input.Email }); + return; + } + + await SignInManager.SignInAsync(user, isPersistent: false, _externalLoginInfo.LoginProvider); + RedirectManager.RedirectTo(ReturnUrl); + return; + } + } + else + { + _message = $"Error: {string.Join(",", result.Errors.Select(error => error.Description))}"; + } + } + + private ApplicationUser CreateUser() + { + try + { + return Activator.CreateInstance(); + } + catch + { + throw new InvalidOperationException($"Can't create an instance of '{nameof(ApplicationUser)}'. " + + $"Ensure that '{nameof(ApplicationUser)}' is not an abstract class and has a parameterless constructor"); + } + } + + private IUserEmailStore GetEmailStore() + { + if (!UserManager.SupportsUserEmail) + { + throw new NotSupportedException("The default UI requires a user store with email support."); + } + return (IUserEmailStore)UserStore; + } + + private sealed class InputModel + { + [Required] + [EmailAddress] + public string? Email { get; set; } + } +} diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/ForgotPassword.razor b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/ForgotPassword.razor new file mode 100644 index 000000000000..605a676daad5 --- /dev/null +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/ForgotPassword.razor @@ -0,0 +1,74 @@ +@page "/Account/ForgotPassword" + +@using System.ComponentModel.DataAnnotations +@using System.Text +@using System.Text.Encodings.Web +@using Microsoft.AspNetCore.Identity +@using Microsoft.AspNetCore.Identity.UI.Services +@using Microsoft.AspNetCore.WebUtilities +@using BlazorWeb_CSharp.Data +@using BlazorWeb_CSharp.Identity + +@inject NavigationManager NavigationManager +@inject IdentityRedirectManager RedirectManager +@inject UserManager UserManager +@inject IEmailSender EmailSender + +Forgot your password? + +

Forgot your password?

+

Enter your email.

+
+
+
+ + + + +
+ + + +
+ +
+
+
+ +@code { + [SupplyParameterFromForm] + private InputModel Input { get; set; } = new(); + + private async Task OnValidSubmitAsync() + { + var user = await UserManager.FindByEmailAsync(Input.Email); + if (user is null || !(await UserManager.IsEmailConfirmedAsync(user))) + { + // Don't reveal that the user does not exist or is not confirmed + RedirectManager.RedirectTo("/Account/ForgotPasswordConfirmation"); + return; + } + + // For more information on how to enable account confirmation and password reset please + // visit https://go.microsoft.com/fwlink/?LinkID=532713 + var code = await UserManager.GeneratePasswordResetTokenAsync(user); + code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); + var callbackUrl = NavigationManager.GetUriWithQueryParameters( + $"{NavigationManager.BaseUri}Account/ResetPassword", + new Dictionary { { "code", code } }); + + await EmailSender.SendEmailAsync( + Input.Email, + "Reset Password", + $"Please reset your password by clicking here."); + + RedirectManager.RedirectTo("/Account/ForgotPasswordConfirmation"); + } + + private sealed class InputModel + { + [Required] + [EmailAddress] + public string Email { get; set; } = default!; + } +} diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/ForgotPasswordConfirmation.razor b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/ForgotPasswordConfirmation.razor new file mode 100644 index 000000000000..38de01d1ec0c --- /dev/null +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/ForgotPasswordConfirmation.razor @@ -0,0 +1,8 @@ +@page "/Account/ForgotPasswordConfirmation" + +Forgot password confirmation + +

Forgot password confirmation

+

+ Please check your email to reset your password. +

diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/InvalidPasswordReset.razor b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/InvalidPasswordReset.razor new file mode 100644 index 000000000000..509578bbf82c --- /dev/null +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/InvalidPasswordReset.razor @@ -0,0 +1,8 @@ +@page "/Account/InvalidPasswordReset" + +Invalid password reset + +

Invalid password reset

+

+ The password reset link is invalid. +

diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/InvalidUser.razor b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/InvalidUser.razor new file mode 100644 index 000000000000..e61fe5def569 --- /dev/null +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/InvalidUser.razor @@ -0,0 +1,7 @@ +@page "/Account/InvalidUser" + +Invalid user + +

Invalid user

+ + diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/Lockout.razor b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/Lockout.razor new file mode 100644 index 000000000000..a8d1e0afc7ca --- /dev/null +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/Lockout.razor @@ -0,0 +1,8 @@ +@page "/Account/Lockout" + +Locked out + +
+

Locked out

+

This account has been locked out, please try again later.

+
diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/Login.razor b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/Login.razor new file mode 100644 index 000000000000..f49edad1beb7 --- /dev/null +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/Login.razor @@ -0,0 +1,133 @@ +@page "/Account/Login" + +@using System.ComponentModel.DataAnnotations +@using System.Text +@using Microsoft.AspNetCore.Authentication +@using Microsoft.AspNetCore.Identity +@using Microsoft.AspNetCore.WebUtilities +@using BlazorWeb_CSharp.Data +@using BlazorWeb_CSharp.Identity + +@inject SignInManager SignInManager +@inject ILogger Logger +@inject NavigationManager NavigationManager +@inject IdentityRedirectManager RedirectManager + +Log in + +

Log in

+
+
+
+ + +

Use a local account to log in.

+
+ +
+ + + +
+
+ + + +
+
+ +
+
+ +
+ +
+
+
+
+
+

Use another service to log in.

+
+ +
+
+
+ +@code { + string? errorMessage; + + [CascadingParameter] + public HttpContext HttpContext { get; set; } = default!; + + [SupplyParameterFromForm] + public InputModel Input { get; set; } = default!; + + [SupplyParameterFromQuery] + public string ReturnUrl { get; set; } = ""; + + public class InputModel + { + [Required] + [EmailAddress] + public string Email { get; set; } = null!; + + [Required] + [DataType(DataType.Password)] + public string Password { get; set; } = null!; + + [Display(Name = "Remember me?")] + public bool RememberMe { get; set; } = false; + } + + protected override async Task OnInitializedAsync() + { + Input ??= new(); + ReturnUrl ??= "/"; + + if (HttpMethods.IsGet(HttpContext.Request.Method)) + { + // Clear the existing external cookie to ensure a clean login process + await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme); + } + } + + public async Task LoginUser() + { + // This doesn't count login failures towards account lockout + // To enable password failures to trigger account lockout, set lockoutOnFailure: true + var result = await SignInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: false); + if (result.Succeeded) + { + Logger.LogInformation("User logged in."); + RedirectManager.RedirectTo(ReturnUrl); + } + if (result.RequiresTwoFactor) + { + RedirectManager.RedirectTo( + "/Account/LoginWith2fa", + new() { ["ReturnUrl"] = ReturnUrl, ["RememberMe"] = Input.RememberMe }); + } + if (result.IsLockedOut) + { + Logger.LogWarning("User account locked out."); + RedirectManager.RedirectTo("/Account/Lockout"); + } + else + { + errorMessage = "Error: Invalid login attempt."; + } + } +} diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/LoginWith2fa.razor b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/LoginWith2fa.razor new file mode 100644 index 000000000000..b1a650544608 --- /dev/null +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/LoginWith2fa.razor @@ -0,0 +1,109 @@ +@page "/Account/LoginWith2fa" + +@using System.ComponentModel.DataAnnotations +@using Microsoft.AspNetCore.Identity +@using BlazorWeb_CSharp.Data +@using BlazorWeb_CSharp.Identity + +@inject SignInManager SignInManager +@inject UserManager UserManager +@inject IdentityRedirectManager RedirectManager +@inject ILogger Logger + +Two-factor authentication + +

Two-factor authentication

+
+ +

Your login is protected with an authenticator app. Enter your authenticator code below.

+
+
+ + + + + +
+ + + +
+
+ +
+
+ +
+
+
+
+

+ Don't have access to your authenticator device? You can + log in with a recovery code. +

+ +@code { + private string? _message; + private ApplicationUser _user = default!; + + [SupplyParameterFromForm] + private InputModel Input { get; set; } = default!; + + [SupplyParameterFromQuery] + private string? ReturnUrl { get; set; } + + [SupplyParameterFromQuery] + private bool RememberMe { get; set; } + + protected override async Task OnInitializedAsync() + { + Input ??= new(); + ReturnUrl ??= "/"; + + var user = await SignInManager.GetTwoFactorAuthenticationUserAsync(); + if (user is null) + { + throw new InvalidOperationException($"Unable to load two-factor authentication user."); + } + + _user = user; + } + + private async Task OnValidSubmitAsync() + { + var authenticatorCode = Input.TwoFactorCode!.Replace(" ", string.Empty).Replace("-", string.Empty); + var result = await SignInManager.TwoFactorAuthenticatorSignInAsync(authenticatorCode, RememberMe, Input.RememberMachine); + var userId = await UserManager.GetUserIdAsync(_user); + + if (result.Succeeded) + { + Logger.LogInformation("User with ID '{UserId}' logged in with 2fa.", _user.Id); + RedirectManager.RedirectTo(ReturnUrl ?? "/"); + } + else if (result.IsLockedOut) + { + Logger.LogWarning("User with ID '{UserId}' account locked out.", _user.Id); + RedirectManager.RedirectTo("/Account/Lockout"); + } + else + { + Logger.LogWarning("Invalid authenticator code entered for user with ID '{UserId}'.", _user.Id); + _message = "Error: Invalid authenticator code."; + } + } + + private sealed class InputModel + { + [Required] + [StringLength(7, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] + [DataType(DataType.Text)] + [Display(Name = "Authenticator code")] + public string? TwoFactorCode { get; set; } + + [Display(Name = "Remember this machine")] + public bool RememberMachine { get; set; } + } +} diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/LoginWithRecoveryCode.razor b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/LoginWithRecoveryCode.razor new file mode 100644 index 000000000000..41d5d3660810 --- /dev/null +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/LoginWithRecoveryCode.razor @@ -0,0 +1,94 @@ +@page "/Account/LoginWithRecoveryCode" + +@using System.ComponentModel.DataAnnotations +@using Microsoft.AspNetCore.Identity +@using Microsoft.AspNetCore.Mvc +@using BlazorWeb_CSharp.Data +@using BlazorWeb_CSharp.Identity + +@inject SignInManager SignInManager +@inject UserManager UserManager +@inject IdentityRedirectManager RedirectManager +@inject ILogger Logger + +Recovery code verification + +

Recovery code verification

+
+ +

+ You have requested to log in with a recovery code. This login will not be remembered until you provide + an authenticator app code at log in or disable 2FA and log in again. +

+
+
+ + + +
+ + + +
+ +
+
+
+ +@code { + private string? _message; + private ApplicationUser _user = default!; + + [SupplyParameterFromForm] + private InputModel Input { get; set; } = default!; + + [SupplyParameterFromQuery] + private string? ReturnUrl { get; set; } + + protected override async Task OnInitializedAsync() + { + Input ??= new(); + + // Ensure the user has gone through the username & password screen first + var user = await SignInManager.GetTwoFactorAuthenticationUserAsync(); + if (user is null) + { + throw new InvalidOperationException($"Unable to load two-factor authentication user."); + } + + _user = user; + } + + private async Task OnValidSubmitAsync() + { + var recoveryCode = Input.RecoveryCode!.Replace(" ", string.Empty); + + var result = await SignInManager.TwoFactorRecoveryCodeSignInAsync(recoveryCode); + + var userId = await UserManager.GetUserIdAsync(_user); + + if (result.Succeeded) + { + Logger.LogInformation("User with ID '{UserId}' logged in with a recovery code.", _user.Id); + RedirectManager.RedirectTo(ReturnUrl ?? "/"); + } + if (result.IsLockedOut) + { + Logger.LogWarning("User account locked out."); + RedirectManager.RedirectTo("/Account/Lockout"); + } + else + { + Logger.LogWarning("Invalid recovery code entered for user with ID '{UserId}' ", _user.Id); + _message = "Error: Invalid recovery code entered."; + } + } + + private sealed class InputModel + { + [Required] + [DataType(DataType.Text)] + [Display(Name = "Recovery Code")] + public string? RecoveryCode { get; set; } + } +} diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/Manage/ChangePassword.razor b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/Manage/ChangePassword.razor new file mode 100644 index 000000000000..aabf71983a62 --- /dev/null +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/Manage/ChangePassword.razor @@ -0,0 +1,97 @@ +@page "/Account/Manage/ChangePassword" + +@using System.ComponentModel.DataAnnotations +@using Microsoft.AspNetCore.Identity +@using BlazorWeb_CSharp.Data +@using BlazorWeb_CSharp.Identity + +@inject UserManager UserManager +@inject SignInManager SignInManager +@inject UserAccessor UserAccessor +@inject IdentityRedirectManager RedirectManager +@inject ILogger Logger + +Change password + +

Change password

+ +
+
+ + + +
+ + + +
+
+ + + +
+
+ + + +
+ +
+
+
+ +@code { + private string? _message; + private ApplicationUser _user = default!; + private bool _hasPassword; + + [SupplyParameterFromForm] + private InputModel Input { get; set; } = default!; + + protected override async Task OnInitializedAsync() + { + Input ??= new(); + + _user = await UserAccessor.GetRequiredUserAsync(); + _hasPassword = await UserManager.HasPasswordAsync(_user); + if (!_hasPassword) + { + RedirectManager.RedirectTo("/Account/Manage/SetPassword"); + return; + } + } + + private async Task OnValidSubmitAsync() + { + var changePasswordResult = await UserManager.ChangePasswordAsync(_user, Input.OldPassword!, Input.NewPassword!); + if (!changePasswordResult.Succeeded) + { + _message = $"Error: {string.Join(",", changePasswordResult.Errors.Select(error => error.Description))}"; + return; + } + + await SignInManager.RefreshSignInAsync(_user); + Logger.LogInformation("User changed their password successfully."); + + RedirectManager.RedirectToCurrentPageWithStatus("Your password has been changed"); + } + + private sealed class InputModel + { + [Required] + [DataType(DataType.Password)] + [Display(Name = "Current password")] + public string? OldPassword { get; set; } + + [Required] + [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] + [DataType(DataType.Password)] + [Display(Name = "New password")] + public string? NewPassword { get; set; } + + [DataType(DataType.Password)] + [Display(Name = "Confirm new password")] + [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")] + public string? ConfirmPassword { get; set; } + } +} diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/Manage/DeletePersonalData.razor b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/Manage/DeletePersonalData.razor new file mode 100644 index 000000000000..c3ed9c38635a --- /dev/null +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/Manage/DeletePersonalData.razor @@ -0,0 +1,85 @@ +@page "/Account/Manage/DeletePersonalData" + +@using System.ComponentModel.DataAnnotations +@using Microsoft.AspNetCore.Identity +@using BlazorWeb_CSharp.Data +@using BlazorWeb_CSharp.Identity + +@inject UserManager UserManager +@inject SignInManager SignInManager +@inject UserAccessor UserAccessor +@inject IdentityRedirectManager RedirectManager +@inject ILogger Logger + +Delete Personal Data + + + +

Delete Personal Data

+ + + +
+ + + + @if (_requirePassword) + { +
+ + + +
+ } + +
+
+ +@code { + private string? _message; + private ApplicationUser _user = default!; + private bool _requirePassword; + + [SupplyParameterFromForm] + private InputModel Input { get; set; } = default!; + + protected override async Task OnInitializedAsync() + { + Input ??= new(); + + _user = await UserAccessor.GetRequiredUserAsync(); + _requirePassword = await UserManager.HasPasswordAsync(_user); + } + + private async Task OnValidSubmitAsync() + { + if (_requirePassword && !await UserManager.CheckPasswordAsync(_user, Input.Password!)) + { + _message = "Error: Incorrect password."; + return; + } + + var result = await UserManager.DeleteAsync(_user); + var userId = await UserManager.GetUserIdAsync(_user); + if (!result.Succeeded) + { + throw new InvalidOperationException($"Unexpected error occurred deleting user."); + } + + await SignInManager.SignOutAsync(); + + Logger.LogInformation("User with ID '{UserId}' deleted themselves.", userId); + + RedirectManager.RedirectToCurrentPage(); + } + + private sealed class InputModel + { + [DataType(DataType.Password)] + public string? Password { get; set; } + } +} diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/Manage/Disable2fa.razor b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/Manage/Disable2fa.razor new file mode 100644 index 000000000000..562b5ca26577 --- /dev/null +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/Manage/Disable2fa.razor @@ -0,0 +1,68 @@ +@page "/Account/Manage/Disable2fa" + +@using Microsoft.AspNetCore.Identity +@using BlazorWeb_CSharp.Data +@using BlazorWeb_CSharp.Identity + +@inject UserManager UserManager +@inject UserAccessor UserAccessor +@inject IdentityRedirectManager RedirectManager +@inject ILogger Logger + +Disable two-factor authentication (2FA) + + +

Disable two-factor authentication (2FA)

+ + + +
+
+ + + +
+ +@code { + private ApplicationUser _user = default!; + + [CascadingParameter] + private HttpContext HttpContext { get; set; } = default!; + + protected override async Task OnInitializedAsync() + { + _user = await UserAccessor.GetRequiredUserAsync(); + + if (HttpMethods.IsGet(HttpContext.Request.Method)) + { + if (!await UserManager.GetTwoFactorEnabledAsync(_user)) + { + throw new InvalidOperationException($"Cannot disable 2FA for user as it's not currently enabled."); + } + return; + } + } + + private async Task OnSubmitAsync() + { + var disable2faResult = await UserManager.SetTwoFactorEnabledAsync(_user, false); + if (!disable2faResult.Succeeded) + { + throw new InvalidOperationException($"Unexpected error occurred disabling 2FA."); + } + + var userId = await UserManager.GetUserIdAsync(_user); + Logger.LogInformation("User with ID '{UserId}' has disabled 2fa.", userId); + RedirectManager.RedirectToWithStatus( + "/Account/Manage/TwoFactorAuthentication", + "2fa has been disabled. You can reenable 2fa when you setup an authenticator app"); + } +} diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/Manage/Email.razor b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/Manage/Email.razor new file mode 100644 index 000000000000..c629d0a8ee8e --- /dev/null +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/Manage/Email.razor @@ -0,0 +1,123 @@ +@page "/Account/Manage/Email" + +@using System.ComponentModel.DataAnnotations +@using System.Text +@using System.Text.Encodings.Web +@using Microsoft.AspNetCore.Identity +@using Microsoft.AspNetCore.Identity.UI.Services +@using Microsoft.AspNetCore.WebUtilities +@using BlazorWeb_CSharp.Data +@using BlazorWeb_CSharp.Identity + +@inject UserManager UserManager +@inject UserAccessor UserAccessor +@inject IEmailSender EmailSender +@inject NavigationManager NavigationManager +@inject IdentityRedirectManager RedirectManager + +Manage email + +

Manage email

+ + +
+
+
+ + + + + + @if (_isEmailConfirmed) + { +
+ +
+ +
+ +
+ } + else + { +
+ + + +
+ } +
+ + + +
+ +
+
+
+ +@code { + private ApplicationUser _user = default!; + private string? _email; + private bool _isEmailConfirmed; + + [SupplyParameterFromForm] + private InputModel Input { get; set; } = default!; + + protected override async Task OnInitializedAsync() + { + Input ??= new(); + + _user = await UserAccessor.GetRequiredUserAsync(); + _email = await UserManager.GetEmailAsync(_user); + _isEmailConfirmed = await UserManager.IsEmailConfirmedAsync(_user); + + Input.NewEmail ??= _email; + } + + private async Task OnValidSubmitAsync() + { + if (Input.NewEmail != _email) + { + var userId = await UserManager.GetUserIdAsync(_user); + var code = await UserManager.GenerateChangeEmailTokenAsync(_user, Input.NewEmail!); + code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); + var callbackUrl = NavigationManager.GetUriWithQueryParameters( + $"{NavigationManager.BaseUri}Account/ConfirmEmailChange", + new Dictionary { { "userId", userId }, { "email", Input.NewEmail }, { "code", code } }); + await EmailSender.SendEmailAsync( + Input.NewEmail!, + "Confirm your email", + $"Please confirm your account by clicking here."); + + RedirectManager.RedirectToCurrentPageWithStatus("Confirmation link to change email sent. Please check your email."); + return; + } + + RedirectManager.RedirectToCurrentPageWithStatus("Your email is unchanged."); + } + + private async Task OnSendEmailVerificationAsync() + { + var userId = await UserManager.GetUserIdAsync(_user); + var code = await UserManager.GenerateEmailConfirmationTokenAsync(_user); + code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); + var callbackUrl = NavigationManager.GetUriWithQueryParameters( + $"{NavigationManager.BaseUri}Account/ConfirmEmail", + new Dictionary { { "userId", userId }, { "code", code } }); + await EmailSender.SendEmailAsync( + _email!, + "Confirm your email", + $"Please confirm your account by clicking here."); + + RedirectManager.RedirectToCurrentPageWithStatus("Verification email sent. Please check your email."); + } + + private sealed class InputModel + { + [Required] + [EmailAddress] + [Display(Name = "New email")] + public string? NewEmail { get; set; } + } +} diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/Manage/EnableAuthenticator.razor b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/Manage/EnableAuthenticator.razor new file mode 100644 index 000000000000..52b3f0d68c5a --- /dev/null +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/Manage/EnableAuthenticator.razor @@ -0,0 +1,174 @@ +@page "/Account/Manage/EnableAuthenticator" + +@using System.ComponentModel.DataAnnotations +@using System.Globalization +@using System.Text +@using System.Text.Encodings.Web +@using Microsoft.AspNetCore.Identity +@using BlazorWeb_CSharp.Data +@using BlazorWeb_CSharp.Identity + +@inject UserManager UserManager +@inject UserAccessor UserAccessor +@inject UrlEncoder UrlEncoder +@inject IdentityRedirectManager RedirectManager +@inject ILogger Logger + +Configure authenticator app + +@if (_recoveryCodes is not null) +{ + +} +else +{ + +

Configure authenticator app

+
+

To use an authenticator app go through the following steps:

+
    +
  1. +

    + Download a two-factor authenticator app like Microsoft Authenticator for + Android and + iOS or + Google Authenticator for + Android and + iOS. +

    +
  2. +
  3. +

    Scan the QR Code or enter this key @_sharedKey into your two factor authenticator app. Spaces and casing do not matter.

    + +
    +
    +
  4. +
  5. +

    + Once you have scanned the QR code or input the key above, your two factor authentication app will provide you + with a unique code. Enter the code in the confirmation box below. +

    +
    +
    + + +
    + + + +
    + + +
    +
    +
    +
  6. +
+
+} + +@code { + private const string AuthenticatorUriFormat = "otpauth://totp/{0}:{1}?secret={2}&issuer={0}&digits=6"; + + private ApplicationUser _user = default!; + private string? _sharedKey; + private string? _authenticatorUri; + + private IEnumerable? _recoveryCodes; + private string? _message; + + [SupplyParameterFromForm] + private InputModel Input { get; set; } = default!; + + protected override async Task OnInitializedAsync() + { + Input ??= new(); + + _user = await UserAccessor.GetRequiredUserAsync(); + + await LoadSharedKeyAndQrCodeUriAsync(_user); + } + + private async Task OnValidSubmitAsync() + { + // Strip spaces and hyphens + var verificationCode = Input.Code!.Replace(" ", string.Empty).Replace("-", string.Empty); + + var is2faTokenValid = await UserManager.VerifyTwoFactorTokenAsync( + _user, UserManager.Options.Tokens.AuthenticatorTokenProvider, verificationCode); + + if (!is2faTokenValid) + { + await LoadSharedKeyAndQrCodeUriAsync(_user); + RedirectManager.RedirectToCurrentPageWithStatus("Error: Verification code is invalid."); + return; + } + + await UserManager.SetTwoFactorEnabledAsync(_user, true); + var userId = await UserManager.GetUserIdAsync(_user); + Logger.LogInformation("User with ID '{UserId}' has enabled 2FA with an authenticator app.", userId); + + _message = "Your authenticator app has been verified."; + + if (await UserManager.CountRecoveryCodesAsync(_user) == 0) + { + _recoveryCodes = await UserManager.GenerateNewTwoFactorRecoveryCodesAsync(_user, 10); + } + else + { + RedirectManager.RedirectToWithStatus("/Account/Manage/TwoFactorAuthentication", _message); + } + } + + private async ValueTask LoadSharedKeyAndQrCodeUriAsync(ApplicationUser user) + { + // Load the authenticator key & QR code URI to display on the form + var unformattedKey = await UserManager.GetAuthenticatorKeyAsync(user); + if (string.IsNullOrEmpty(unformattedKey)) + { + await UserManager.ResetAuthenticatorKeyAsync(user); + unformattedKey = await UserManager.GetAuthenticatorKeyAsync(user); + } + + _sharedKey = FormatKey(unformattedKey!); + + var email = await UserManager.GetEmailAsync(user); + _authenticatorUri = GenerateQrCodeUri(email!, unformattedKey!); + } + + private string FormatKey(string unformattedKey) + { + var result = new StringBuilder(); + int currentPosition = 0; + while (currentPosition + 4 < unformattedKey.Length) + { + result.Append(unformattedKey.AsSpan(currentPosition, 4)).Append(' '); + currentPosition += 4; + } + if (currentPosition < unformattedKey.Length) + { + result.Append(unformattedKey.AsSpan(currentPosition)); + } + + return result.ToString().ToLowerInvariant(); + } + + private string GenerateQrCodeUri(string email, string unformattedKey) + { + return string.Format( + CultureInfo.InvariantCulture, + AuthenticatorUriFormat, + UrlEncoder.Encode("Microsoft.AspNetCore.Identity.UI"), + UrlEncoder.Encode(email), + unformattedKey); + } + + private sealed class InputModel + { + [Required] + [StringLength(7, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] + [DataType(DataType.Text)] + [Display(Name = "Verification Code")] + public string? Code { get; set; } + } +} diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/Manage/ExternalLogins.razor b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/Manage/ExternalLogins.razor new file mode 100644 index 000000000000..4ff1ec38044a --- /dev/null +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWeb-CSharp/Components/Pages/Account/Manage/ExternalLogins.razor @@ -0,0 +1,152 @@ +@page "/Account/Manage/ExternalLogins" + +@using Microsoft.AspNetCore.Authentication +@using Microsoft.AspNetCore.Identity +@using Microsoft.AspNetCore.Mvc.ViewFeatures +@using BlazorWeb_CSharp.Data +@using BlazorWeb_CSharp.Identity + +@inject UserManager UserManager +@inject SignInManager SignInManager +@inject UserAccessor UserAccessor +@inject IUserStore UserStore +@inject IdentityRedirectManager RedirectManager + +Manage your external logins + + +@if (_currentLogins?.Count > 0) +{ +

Registered Logins

+ + + @foreach (var login in _currentLogins) + { + + + + + } + +
@login.ProviderDisplayName + @if (_showRemoveButton) + { +
+ +
+ + + +
+ + } + else + { + @:   + } +
+} +@if (_otherLogins?.Count > 0) +{ +

Add another service to log in.

+
+