【问题标题】:Blazor: Adding a custom AuthenticationStateProvider in Startup.cs not recognizedBlazor:在 Startup.cs 中添加自定义 AuthenticationStateProvider 无法识别
【发布时间】:2019-08-24 16:08:24
【问题描述】:

我正在尝试使用自定义数据库实现登录。据我所知,我需要重写 AuthenticationStateProvider 才能完成此操作。

在 MyServerAuthenticationStateProvider.cs 中:

public class MyServerAuthenticationStateProvider : 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 中:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using BadgerWatchWeb.Services;

namespace BadgerWatchWeb
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddRazorPages();
        services.AddServerSideBlazor();
        services.AddSingleton<UserService>();
        services.AddAuthorizationCore();
        services.AddScoped<AuthenticationStateProvider, MyServerAuthenticationStateProvider > ();
        //services.AddScoped<AuthenticationStateProvider>(provider => provider.GetRequiredService<MysServerAuthenticationStateProvider>());
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
        }

        app.UseStaticFiles();
        app.UseAuthentication();
        app.UseAuthorization();

        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapBlazorHub<App>(selector: "app");
            endpoints.MapFallbackToPage("/_Host");
        });
    }
}

}

当我尝试在 .razor 类中使用此服务时,我收到一条错误消息,提示“MyServerAuthenticationStateProvider 不包含 LoadUser 的定义。”

@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();
    }

}

我不确定我是否没有正确使用 AuthenticationStateProvider,并且我无法在网上找到任何有关如何在 razor 中实现自定义登录的示例。但我的问题是:为什么我的代码无法识别 LoadUser,即使 MyServerAuthenticationProvider 在 Startus.cs 中被声明为 AuthenticationStateProvider 的范围。

【问题讨论】:

    标签: c# blazor


    【解决方案1】:

    在 DI 上,您做了正确的事情来注入您的自定义提供程序:

        services.AddScoped<AuthenticationStateProvider, 
                           MyServerAuthenticationStateProvider > ();
    

    要访问您的自定义提供程序,只需进行强制转换:

    @inject AuthenticationStateProvider AuthenticationStateProvider
    
    @code {
    
    
    protected override async Task OnInitializedAsync()
    {
        var myStateProv = AuthenticationStateProvider as
                            MyServerAuthenticationStateProvider;
        myStateProv.LoadUser("mperry", "testtest");
    

    已编辑(2020 年 10 月)

    或:

        services.AddAuthorizationCore();
    
        services.AddScoped<
          MyServerAuthenticationStateProvider,
          MyServerAuthenticationStateProvider>();
    
        services.AddScoped<AuthenticationStateProvider>(
          p => p.GetService<MyServerAuthenticationStateProvider>() );
    

    然后通过 DI 获得它:

    @inject MyServerAuthenticationStateProvider MyAuthenticationStateProvider
    

    【讨论】:

    • &lt;AuthorizeView&gt; &lt;Authorized&gt; 标签仍然不起作用。我错过了什么吗?
    • 评论与您的​​问题无关。只需打开一个具有新要求的新问题。它是免费的。
    • 你错过的不仅仅是一些东西......请创建一个新问题,正如@dani 建议的那样......事实上,你的问题应该类似于当前的问题,在至少它应该包含相同的引用代码,我会尝试一次,以结束你的痛苦。
    • 我可以确认这行得通!几天来我一直在思考为什么IsAuthenticated 会返回false,即使我的ClaimsIdentity 构造函数中有身份验证类型。
    猜你喜欢
    • 2015-02-01
    • 2021-11-17
    • 2020-03-25
    • 2020-04-18
    • 2022-06-22
    • 2023-03-25
    • 2021-11-29
    • 2019-08-27
    • 2016-01-30
    相关资源
    最近更新 更多