Blazor 是一种 WebAssembly 执行的客户端 Web 开发框架,允许在浏览器中运行 .NET 代码。在 Blazor WebAssembly 应用程序中,最佳实践是使用身份验证和授权系统来保护应用程序中的资源。本文将分享如何在 Blazor WebAssembly 应用程序中实现用户账户和 Identity 服务器的最佳实践。
安装命令: Install-Package Microsoft.AspNetCore.Components.WebAssembly.Authentication
安装命令: Install-Package Microsoft.Identity.Web
// using Microsoft.AspNetCore.Authorization; // using Microsoft.AspNetCore.Components.WebAssembly.Authentication; // using Microsoft.AspNetCore.Components.WebAssembly.Hosting; // using Microsoft.Extensions.Configuration; // using Microsoft.Extensions.DependencyInjection; // using Microsoft.Extensions.Logging; // using System; // using System.Net.Http; // using System.Threading.Tasks;
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
builder.Services.AddOptions(); builder.Services.AddAuthorizationCore(); builder.Services.AddHttpClient("ServerAPI", client => client.BaseAddress = new Uri("https://localhost:44333/api/"));
builder.Services.AddOidcAuthentication(options => { builder.Configuration.Bind("Local", options.ProviderOptions); });
builder.RootComponents.Add
await builder.Build().RunAsync();
这里使用的是 OpenID Connect (OIDC) 身份验证,可以在 appsettings.json 文件中添加 Local 元素来配置 OIDC 设置。
"Local": { "Authority": "https://localhost:44328", "ClientId": "blazor_app_client", "DefaultScopes": [ "openid", "profile", "email",