【发布时间】:2021-11-29 18:46:39
【问题描述】:
大家好! 我正在尝试在 Blazor WebAssembly 应用程序中创建我的自定义身份验证模式(这是工作室创建 3 个项目的地方 - 客户端、服务器、共享)。想法是避免 IS4 身份验证,让我的“内部”用户用于测试目的,并了解身份验证机的工作。我通过创建我的自定义 AuthenticationStateProvider 来做到这一点?就像official docs 中显示的一样。这是我的 AuthenticationStateProvider 类:
public class CustomAuthStateProvider : AuthenticationStateProvider
{
private bool _isLoggedIn = true;
//this is a parameter defininng whether user logged in or not
//changed by reflection
public bool IsLoggedIn
{
get
{
return _isLoggedIn;
}
set
{
_isLoggedIn = value;
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
}
}
private static CustomAuthStateProvider _myInstance = null;
public Serilog.ILogger _logger { get; set; }
public override Task<AuthenticationState> GetAuthenticationStateAsync()
{
ClaimsIdentity identity;
Task<AuthenticationState> rez;
if (IsLoggedIn)
{
identity = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, "User01"),
}, "Fake authentication type");
}
else
{
identity = new ClaimsIdentity();
}
var user = new ClaimsPrincipal(identity);
rez = Task.FromResult(new AuthenticationState(user));
return rez;
}
public static CustomAuthStateProvider GetMyInstance(Serilog.ILogger logger = null, string mySide = "")
{
//implementing singleton
if (_myInstance == null)
{
_myInstance = new CustomAuthStateProvider();
_myInstance._logger = logger;
}
return _myInstance;
}
}
这就是我将它插入客户端(program.cs)的方式
builder.Services.AddSingleton<AuthenticationStateProvider>(x => CustomAuthStateProvider.GetMyInstance(Log.Logger, "Client"));
这就是我将它插入服务器端 (startup.cs) 的方式
services.AddSingleton<AuthenticationStateProvider, CustomAuthStateProvider>();
问题: 它在客户端运行良好,这意味着我可以登录、注销并使用 AutorizeView 和类似的标签。但它在服务器端不起作用,这意味着 HttpContext.User 没有看到任何经过身份验证的用户,我不能使用 [Authorize] 和类似属性。我做错了什么? HttpContext.User如何连接到asp.net核心项目中的AuthenticationStateProvider? 谢谢;-)
【问题讨论】:
-
在这里找到类似的问题stackoverflow.com/questions/62529029/…
-
我认为服务注册应该是Scoped的。我还在下面为您添加了我的服务器端授权测试器的代码。我已将其添加为答案,因为这是添加它的唯一方法。
标签: asp.net asp.net-core blazor asp.net-core-webapi blazor-server-side