Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

subscribing to Blazor AuthenticationStateChanged

I could not find any example of how to use the AuthenticationStateChanged in blazor.

My intention is that any page where i want to react to user login or logout i will use these code. I could not find any example on how to implement the event. the one that i tried just keeps on firing for infinite times.

_CustomAuthProvider.AuthenticationStateChanged += AuhtenticationStateChanged;

private async void AuhtenticationStateChanged(Task<AuthenticationState> task)
    {
        //This keeps on executing in in loop.
    }
like image 293
NSS Avatar asked Oct 26 '25 05:10

NSS


1 Answers

I know this is old, but I would have liked an answer when I found it...

This is the code I use on a Blazor web assembly (dotnet 6.0). This is part of a scoped service that I can access through dependency injection from anywhere else in my application.

Notice the await(task) to retrieve the state in the event handler:

public AuthenticationService(AuthenticationStateProvider authenticationProvider, IProfileService profileService)
{
  _profileService = profileService;
  _authenticationProvider = authenticationProvider;
  _authenticationProvider.AuthenticationStateChanged += AuthenticationStateChangedHandler;

  // perform initial call into the event handler
  AuthenticationStateChangedHandler(_authenticationProvider.GetAuthenticationStateAsync());
}

private bool _disposed = false;

public void Dispose()
{
  if  (!_disposed)
  {
    _disposed = true;
    _authenticationProvider.AuthenticationStateChanged -= AuthenticationStateChangedHandler;
  }
}

public event AuthenticationChanged? AuthenticationChanged;
public AuthenticationState? AuthenticationState { get; private set; }

private async void AuthenticationStateChangedHandler(Task<AuthenticationState> task)
{
  AuthenticationState = await (task);
  if (IsAuthenticated)
  {
    // first load profile
    await _profileService.LoadProfile(UserName!);
  }
  else
  {
    await _profileService.EmptyProfile();
  }
  // then update all listening clients, invoke the event
  AuthenticationChanged?.Invoke(AuthenticationState);
}
like image 129
Christian Lavigne Avatar answered Oct 28 '25 04:10

Christian Lavigne