How to run code on login in Blazor WebAssembly?

Viewed 1014

I'm trying to run a function every time a user logs in. What I tried is to obtain an instance of AuthenticationStateProvider from the DI container and subscribe to its AuthenticationStateChanged event. The problem is that my login pages are implemented using server-rendered Razor Pages so the page refreshes after a successful login. This means that my code subscribes to the event after it is fired, so my handler function never runs. Can anybody see a way to run custom code upon successful login?

2 Answers

If you're using the token based authentication (API), you can attach an event handler to the RemoteAuthenticatorView component located in the Authentication component. I think it has an event that is invoked immediately after a user log in. As far as I recall, I've once answered a similar question that way, and then changed my answer to something more useful. Try this solution, and let us know if it's OK.

You can inject the AuthorizationService into your component and then await the AuthenticationState to run code if your user is logged in. Further details are in the documentation here.

@using Microsoft.AspNetCore.Authorization
@inject IAuthorizationService AuthorizationService

<button @onclick="@DoSomething">Do something important</button>

@code {
    [CascadingParameter]
    private Task<AuthenticationState> authenticationStateTask { get; set; }

    private async Task DoSomething()
    {
        var user = (await authenticationStateTask).User;

        if (user.Identity.IsAuthenticated)
        {
            // Perform an action only available to authenticated (signed-in) users.
        }
    }
}

Instead of an onclick handler you can put the auth check in a component's initializedasync method or wherever else is appropriate.

Another approach is to hook into the OnLoginSucceeded property of the RemoteAuthenticatorView, like:

<RemoteAuthenticatorView Action="@Action" OnLogInSucceeded="OnLoginSucceeded" />
@code{
    [Parameter] public string Action { get; set; }

    private void OnLoginSucceeded() 
    {
        // do your stuff here
    }
}
Related