Blazor是一个用于构建Web应用程序的.NET框架。Blazor分为两种模式:Blazor WASM(WebAssembly)和Blazor Server。Blazor WASM是在客户端运行的,而Blazor Server则在服务器上运行,并使用SignalR进行实时通信。
以下是Blazor WASM和Blazor Server中的认证示例代码:
Blazor WASM认证:
dotnet new blazorwasm -n MyProject
cd MyProject
dotnet add package Microsoft.AspNetCore.Components.WebAssembly.Authentication
Program.cs
文件中配置认证服务:using Microsoft.AspNetCore.Components.WebAssembly.Authentication;
builder.Services.AddHttpClient("MyProject.ServerAPI", client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))
.AddHttpMessageHandler();
builder.Services.AddScoped(sp => sp.GetRequiredService().CreateClient("MyProject.ServerAPI"));
builder.Services.AddApiAuthorization();
await builder.Build().RunAsync();
App.razor
文件中添加对认证组件的引用:
Sorry, there's nothing at this address.
Blazor Server认证:
dotnet new blazorserver -n MyProject
cd MyProject
dotnet add package Microsoft.AspNetCore.Components.Server
Startup.cs
文件中配置认证服务:using Microsoft.AspNetCore.Components.Server;
using Microsoft.AspNetCore.Identity;
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication();
services.AddAuthorization();
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddSingleton();
// 添加身份验证服务
services.AddIdentity()
.AddDefaultUI()
.AddDefaultTokenProviders()
.AddEntityFrameworkStores();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// ...
app.UseAuthentication();
app.UseAuthorization();
// ...
}
_Imports.razor
文件中引入Identity和认证组件:@using Microsoft.AspNetCore.Identity
@using Microsoft.AspNetCore.Components.Authorization
@using Microsoft.AspNetCore.Components.Server
Login.razor
:@page "/login"
@inherits LoginDisplayBase
@inject NavigationManager NavigationManager
已登录
登录
请登录以访问该页面。
@code {
private async Task Login()
{
var returnUrl = NavigationManager.ToBaseRelativePath(NavigationManager.Uri);
NavigationManager.NavigateTo($"Identity/Account/Login?returnUrl={returnUrl}", forceLoad: true);
}
}
AuthorizeView
组件:@page "/securepage"
@attribute [Authorize]
安全页面
只有经过身份验证的用户才能访问该页面。
以上是Blazor WASM和Blazor Server中的认证示例代码。你可以根据这些示例代码来实现Blazor应用程序的认证功能。