1.创建一个包含用户登录信息的用户表格。例如:
CREATE TABLE [dbo].[Users]( [Id] [int] IDENTITY(1,1) NOT NULL, [Username] nvarchar NOT NULL, [Password] nvarchar NOT NULL, [Role] [int] NOT NULL, CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED ([Id] ASC) )
2.在Blazor应用程序中使用ASP.NET Core Identity进行身份验证。
3.在客户端项目中添加以下包:
Microsoft.AspNetCore.Components.WebAssembly.Authentication
4.在程序启动的时候,将appsettings.json文件中的用户登录信息加载到内存中。例如:
builder.Services.AddHttpClient("ServerAPI", client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))
.AddHttpMessageHandler(sp =>
{
var handler = sp.GetService
builder.Services.AddSingleton( new HttpClient( new HttpClientHandler { ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator }) { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
// Load user login information from appsettings.json.
var userSection = Configuration.GetSection("User");
if (userSection.Exists())
{
var users = userSection.Get>();
if (users != null)
{
foreach (var user in users)
{
builder.Services.AddSingleton(user);
}
}
}
5.在Blazor的页面中使用AuthenticationStateProvider获取用户的身份信息。例如:
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication @using Microsoft.AspNetCore.Components.Authorization @inject AuthenticationStateProvider AuthenticationStateProvider
@code { private bool isAuthenticated; private string username; private string password;
protected override async Task OnInitializedAsync()
{
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
isAuthenticated