在Blazor中:
我正在创建自定义AuthenticationStateProvider类,因此可以使用mssql上托管的自定义用户数据库。我的自定义类是:
public class ServerAuthenticationStateProvider : AuthenticationStateProvider
{
string UserId;
string Password;
public void LoadUser(string _UserId, string _Password)
{
UserId = _UserId;
Password = _Password;
}
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
{
var securityService = new SharedServiceLogic.Security();
var userService = new UserService();
var validPassword = await securityService.ValidatePassword(UserId, Password);
var authenticated = validPassword == true ? true : false;
var identity = authenticated
? new ClaimsIdentity(await userService.GetClaims(UserId), "AuthCheck")
: new ClaimsIdentity();
var result = new AuthenticationState(new ClaimsPrincipal(identity));
return result;
}
}
然后我在Startup.cs中注册它:
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddSingleton<UserService>();
services.AddAuthorizationCore();
services.AddScoped<AuthenticationStateProvider, ServerAuthenticationStateProvider>();
}
我的App.razor是:
<CascadingAuthenticationState>
<Router AppAssembly="typeof(Startup).Assembly">
<NotFoundContent>
<p>Sorry, there's nothing at this address.</p>
</NotFoundContent>
</Router>
</CascadingAuthenticationState>
现在我要在Index.razor中使用该服务:
@page "/"
@using BadgerWatchWeb.Services
@inject AuthenticationStateProvider AuthenticationStateProvider
<h1>Sup</h1>
<AuthorizeView>
<Authorized>
<h1>Hello, @context.User.Identity.Name!</h1>
<p>You can only see this content if you're authenticated.</p>
</Authorized>
<NotAuthorized>
<h1>Authentication Failure!</h1>
<p>You're not signed in.</p>
</NotAuthorized>
<Authorizing>
<h1>Authorizing</h1>
</Authorizing>
</AuthorizeView>
@code {
[CascadingParameter] Task<AuthenticationState> authenticationStateTask { get; set; }
AuthenticationState AuthState;
protected override async Task OnInitializedAsync()
{
AuthenticationStateProvider.LoadUser("mperry", "testtest");
AuthState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
Console.WriteLine(AuthState);
}
}
由于错误,我无法运行此代码。错误显示AuthenticationStateProvider does not contain a definition of LoadUser
。我认为该服务将能够使用ServerAuthenticationStateProvider中的类。不是吗?
答案 0 :(得分:1)
ServerAuthenticationStateProvider 是Blazor在服务器端Blazor configuration中添加的默认AuthenticationStateProvider的名称,实际上,它不包含LoadUser的定义
这是史蒂夫·安德森(Steve Anderson)关于自定义AuthenticationStateProvider的话
对于服务器端Blazor,您不太可能实施 自定义AuthenticationStateProvider。内置实现 已经与ASP.NET Core的内置身份验证集成 机制。如果实施自定义,则可能会引入安全性 漏洞。
我建议您通读ServerAuthenticationStateProvider类,了解它的作用和方式,遵循整个过程,然后决定是否创建自定义的AuthenticationStateProvider
希望这会有所帮助