我有以下问题。
我需要使用用户名/密码来实现服务器端的blazor认证。
所以我的CustomAuthStateProvider:
using Microsoft.AspNetCore.Components;
using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
namespace Test
{
public class CustomAuthStateProvider : AuthenticationStateProvider
{
private AppState appState;
public CustomAuthStateProvider(AppState _appState)
{
appState = _appState;
}
public override Task<AuthenticationState> GetAuthenticationStateAsync()
{
var identity = new ClaimsIdentity();
if (appState.isAuthenticated)
{
identity = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, "Admin"),
}, "Auth");
}
var user = new ClaimsPrincipal(identity);
return Task.FromResult(new AuthenticationState(user));
}
}
}
然后在以下课程中:
public class AppState
{
public bool isAuthenticated { get; set; }
}
在startup.cs中:
services.AddAuthorizationCore();
services.AddScoped<AuthenticationStateProvider, CustomAuthStateProvider>();
services.AddScoped<AppState>;
在登录组件中:
@Inject AppState appState
...
if (await webSiteService.Login(login, password))
{
appState.isAuthenticated = true;
UriHelper.NavigateTo("dashboard", true);
}
我还有一个App.Razor。
但是上面的代码仅在我使用时才有效:
services.AddSingleton();
但是,如果我打开另一个浏览器选项卡,它也将通过身份验证!
您能建议使用正确的模式/方法吗?
非常感谢!
拉斐尔