【发布时间】:2021-04-14 21:59:38
【问题描述】:
我正在尝试开始使用 Blazor Server。请多多包涵 - 这是我迈向网络的第一步。
我的小应用程序只包含一个页面,其中包含一些保存在数据库中的输入字段。为了识别用户,我在 .razor 页面中添加了以下代码:(在代码隐藏中)
public partial class MyPage
{
[Inject] AuthenticationStateProvider AuthenticationStateProvider { get; set; }
protected override async Task OnInitializedAsync()
{
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var user = authState.User;
if (user.Identity.IsAuthenticated)
{
sessionController.UserKid = user.Identity.Name;
}
else
{
//userAuthenticated = "The user is NOT authenticated.";
}
}
…
现在我想添加第二页(以及以后更多)。但是由于我没有一个通用的“登陆页面”,所以我必须在每个页面中重新插入上面的代码! 所以我想在显示页面之前启动应用程序时对用户进行身份验证。在剃须刀组件之外。但现在我不知道在哪里做得最好。这是否属于“startup.cs”?它是如何工作的?
我刚刚尝试了以下方法:我通过以下方式使我的课程“SessionController”可用:
startup.cs:
public void ConfigureServices(IServiceCollection services)
{
…
services.AddScoped<SessionController>();
}
授权被确定并保存在“SessionController”类中:我在构造函数中调用用户认证。
SessionController:
public class SessionController
{
private string _UserKid = "";
public string UserKid
{
get {
return _UserKid;
}
set
{
--> … Fetching User from Database via "value" as key …
_UserKid = value;
}
}
[Inject] AuthenticationStateProvider AuthenticationStateProvider { get; set; }
protected async Task Authorisation()
{
//Why ist it always null ?
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var user = authState.User;
if (user.Identity.IsAuthenticated)
{
this.UserKid = user.Identity.Name;
}
else
{
//userAuthenticated = "The user is NOT authenticated.";
}
}
public SessionController()
{
Authorisation().Wait();
}
}
我的问题:
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync ();
AuthenticationStateProvider 在这里始终为 NULL。 我不太明白为什么。你能帮帮我吗?
非常感谢!
【问题讨论】:
-
看看这个:docs.microsoft.com/en-us/aspnet/core/blazor/security/…:也许考虑使用 AuthorizeView 组件docs.microsoft.com/en-us/dotnet/api/…。您通常不需要直接使用 AuthenticationStateProvider。
-
感谢您的建议!我可以在 razor 组件/页面之外使用 AuthorizeView 吗?
-
如果您想在特定路由上添加身份验证,请添加@attribute [Authorize] 标签(如上面链接中所述)。如果您想在后面的代码中验证当前用户,请在 docs.microsoft.com/en-us/aspnet/core/blazor/security/… 检查 Task
authenticationStateTask 的使用 - 看起来它包含了 AuthenticationStateProvider 的使用