user6684475
user6684475

Reputation:

Blazor: Adding a custom AuthenticationStateProvider in Startup.cs not recognized

I am trying to implement a login using a custom database. As far as I can tell, I need to override AuthenticationStateProvider in order to accomplish this.

In 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;
    }

}

In 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");
        });
    }
}

}

When I then try to use this service in a .razor class, I get an error saying 'MyServerAuthenticationStateProvider does not contain a definition for 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();
    }

}

I am not sure if I am not sure if I am not using AuthenticationStateProvider correctly, and I have not been able to find any examples online of how to implement a custom login in razor. But my question is: why can't my code recognize LoadUser even though MyServerAuthenticationProvider is declaed as scoped to AuthenticationStateProvider in Startus.cs.

Upvotes: 13

Views: 22577

Answers (1)

dani herrera
dani herrera

Reputation: 51655

On DI you did the right thing injecting your custom provider:

    services.AddScoped<AuthenticationStateProvider, 
                       MyServerAuthenticationStateProvider > ();

To access your custom provider, just make a cast:

@inject AuthenticationStateProvider AuthenticationStateProvider

@code {


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

Edited ( october 2020 )

or:

    services.AddAuthorizationCore();

    services.AddScoped<
      MyServerAuthenticationStateProvider,
      MyServerAuthenticationStateProvider>();

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

And just get it via DI:

@inject MyServerAuthenticationStateProvider MyAuthenticationStateProvider

Upvotes: 12

Related Questions