americanslon
americanslon

Reputation: 4288

Where would something that needs to be called first on every page load would go in blazor?

I read the blazor lifecycle doc but I am still not sure where I can put something that I absolutely have to have executed as the first thing on the page load.

For example:

I am implementing a simple login. I use localstorage to save the authenticated user with one of the object fields being the time inserted into local storage so I can compare it to DateTime.Now to see if the object expired should the user hit f5.

The comparison needs to happen as the very first thing on the page load. So I put it into the OnInitialized of the layout page all my pages use. Issue is OnInitialized of the child page gets called before OnInitialized of the layout page and the child expects the user object to already be set to do it's thing.

LoggedIn (main layout)

@inherits LayoutComponentBase;

<!--- material frame --->
            @Body
<!--- /material frame --->

@code
{

    protected override void OnInitialized()
    {
        Console.WriteLine("parent");
    }
}

Exams (child)

@layout WebApp.Shared.Layouts.LoggedIn;

<! --- stuff ----.
@page "/app/examinations"
<! --- /stuff ----.
}

@code {


    protected override void OnInitialized()
    {
         Console.WriteLine("child");
     }

}

Upvotes: 0

Views: 226

Answers (1)

seraphym
seraphym

Reputation: 1146

OnInitialized should not be used to handle authentication. However, Blazor has an authentication framework built in that you can take advantage of:

  1. Implement a custom AuthenticationStateProvider, overriding GetAuthenticationStateAsync with the logic that determines whether or not your user is logged in.
  2. Register your new AuthenticationStateProvider in your client-side startup
  3. Add on the [Authorize] attribute to any page that requires a login

Microsoft full documentation here

Upvotes: 1

Related Questions