Is there any way to access authentication state outside Component ? For example I am trying ,
public class ServersideCurrentUserIdentityProvider : ICurrentUserIdentityProvider, IDisposable
{
private Task<AuthenticationState> currentAuthenticationStateTask;
private readonly AuthenticationStateProvider stateProvider;
public ServersideCurrentUserIdentityProvider(AuthenticationStateProvider stateProvider)
{
this.stateProvider = stateProvider;
stateProvider.AuthenticationStateChanged += OnAuthenticationStateChanged;
currentAuthenticationStateTask = stateProvider.GetAuthenticationStateAsync();
}
private void OnAuthenticationStateChanged(Task<AuthenticationState> task)
{
this.currentAuthenticationStateTask = task;
}
public async Task<ClaimsPrincipal> GetCurrentUserPrincipal()
{
var state = await currentAuthenticationStateTask;
return state.User;
}
public void Dispose()
{
this.stateProvider.AuthenticationStateChanged -= OnAuthenticationStateChanged;
}
}
this class is registered in DI as
services.AddServerSideBlazor();
services.AddScoped<AuthenticationStateProvider, RevalidatingIdentityAuthenticationStateProvider<ApplicationUser>>();
services.AddSingletone<ICurrentUserIdentityProvider,ServersideCurrentUserIdentityProvider>()
I am trying to use CurrentUserProvider as a Parameter to db Context as
public class ExampleDbContext()
{
public ExampleDbContext(DbContextOption opt, ICurrentUserProvider provider){
override Task<int> onSaveChange(){
var principal= await this.userProvider.GetCurrentPrincipal();
foreach ..
entity.CreatedBy=principal.Name;
}
}
When I try to run, I get exception Saying, GetAuthenticationState Should be called After SetAuthentication State, How do I do that ???