I am trying to make a new version of AuthenticationStateProvider so that I can use the data already in my db. I called it ServerAuthenticationStateProvider:
using Microsoft.AspNetCore.Components;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
namespace BadgerWatchWeb.Services
{
public class ServerAuthenticationStateProvider : AuthenticationStateProvider
{
string UserId;
string Password;
bool IsAuthenticated = false;
public void LoadUser(string _UserId, string _Password)
{
UserId = _UserId;
Password = _Password;
}
public async Task LoadUserData()
{
var securityService = new SharedServiceLogic.Security();
try
{
var passwordCheck = await securityService.ValidatePassword(UserId, Password);
IsAuthenticated = passwordCheck == true ? true : false;
} catch(Exception ex)
{
Console.WriteLine(ex);
}
}
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
{
var userService = new UserService();
var identity = IsAuthenticated
? new ClaimsIdentity(await userService.GetClaims(UserId))
: new ClaimsIdentity();
var result = new AuthenticationState(new ClaimsPrincipal(identity));
return result;
}
}
}
My configure services looks like:
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddSingleton<UserService>();
services.AddScoped<AuthenticationStateProvider, ServerAuthenticationStateProvider>();
services.AddAuthorizationCore();
}
I then inject @inject ServerAuthenticationStateProvider AuthenticationStateProvider
into my razor view file.
When I run the code I get InvalidOperationException: Cannot provide a value for property 'AuthenticationStateProvider' on type 'BadgerWatchWeb.Pages.Index'. There is no registered service of type 'BadgerWatchWeb.Services.ServerAuthenticationStateProvider'.
You should replace
@inject ServerAuthenticationStateProvider AuthenticationStateProvider
with
@inject AuthenticationStateProvider AuthenticationStateProvider
because that is how you registered it.