Reputation: 1285
All I want to do is download user data in MainLayout.razor once the user is authenticated, but there is no reliable place to do so.
I really enjoy blazor, but this issue has plagued me for years. Has anyone found a reasonable way to do this? I continue to write hacky ways to solve this, but they cause performance problems.
Here's what im using right now. It causes the page to re-render and runs like 10 times.
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (!Authenticated)
{
Console.WriteLine("MainLayout.Authenticating");
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var user = authState.User;
if (user.Identity is {IsAuthenticated: true})
{
Console.WriteLine("MainLayout.Authenticated");
Authenticated = true;
await StateContainer.LoadMyData();
}
else
{
Console.WriteLine("MainLayout.NotAuthenticated");
}
}
}
Upvotes: 0
Views: 722
Reputation: 447
Depending on how your application is setup, and assuming it uses the authentication state as a cascading parameter, you could simply leverage the AuthorizeView in your MainLayout.
<AuthorizeView>
<Authorized>
<h1>Hello, @context.User.Identity.Name!</h1>
<p>You can only see this content if you are authorized.</p>
<button @onclick="SecureMethod">Authorized Only Button</button>
</Authorized>
<NotAuthorized>
<h1>Authentication Failure!</h1>
<p>You are not signed in.</p>
</NotAuthorized>
</AuthorizeView>
Loading the data inside the component could simply become a component that is called the same way you call your code. But it removes the need to handle the actual state in the MainLayout page.
Here is some more information that would help (from MS) : https://learn.microsoft.com/en-us/aspnet/core/blazor/security/?view=aspnetcore-6.0#expose-the-authentication-state-as-a-cascading-parameter
Note that, when you start cascading the authentication within your application (make sure you implement the CascadingAuthenticationState from your App.razor), then you could use the components everywhere in your application. You only need to care about what you want to show when the user is authorized (or not authorized).
Upvotes: 1