Reputation: 199
In a Blazor Server application, we use simple SQL Server database authentication by storing user details in a table. First route of the application is "https://localhost:44349/login".
We gave mail address and password as credential and it navigates to "https://localhost:44349/valuation".
Everything is Okay until then. We store the user details in session.
await sessionStorage.SetItemAsync("email", result.Email);
await sessionStorage.SetItemAsync("role", result.TipoUtilizador);
await sessionStorage.SetItemAsync("Name", result.Nome);
UriHelper.NavigateTo("valuation");
If we open a new tab, and directly copying the "https://localhost:44349/valuation", there is a problem that needs to addressed.
Copy the link to new tab "https://localhost:44349/valuation" We check session storage value in "OnInitializedAsync" meyhod Now, there is no matching value sessionstorage, it navigates back to login page.
But the problem is, we can see the UI element before it navigates to login page
var email = await sessionStorage.GetItemAsync<string>("email");
if (string.IsNullOrEmpty(email))
{
var returnUrl = Navigation.ToBaseRelativePath(Navigation.Uri);
var destination = string.IsNullOrWhiteSpace(returnUrl) ? "/login" : $"/login?returnUrl={returnUrl}";
Navigation.NavigateTo(destination, true);
}
This h1 tag is from valuation component, it displays before navigates to login page. (in real case, we have lot of HTML controls such as button, selection, etc.. which we want to hide)
I have checked the blazor documentation and found that OnInitializedAsync is invoked after the component is included in render tree and ready for accepting data.
Please help me to overcome this problem for this simple authentication.
Upvotes: 1
Views: 741
Reputation: 7194
Wrap the elements you don't want visible until the user is authenticated in an <AuthorizeView></AuthorizeView>
element.
Upvotes: 1