I created a Blazor server web app with .NET 8.0 and authentication type Individual Accounts. The web app code is generated automatically by Visual Studio 2022. Everything works fine as expected.
However I would like to change the code so that when a user accesses the web app, it shows the login page and makes sure the user is authenticated before he/she can access the content of the web site.
I have tried to add the following lines (according to a suggestion on Google search)
@using Microsoft.AspNetCore.Authorization
@attribute [Authorize]
to _imports.razor according a suggestion on Google search but I got an error – can’t read this page
"It looks like the webpage at https://localhost:7145/Account/Login?ReturnUrl=%2FAccount%2FLogin%3FReturnUrl%3D%252FAccount%252FLogin%253FReturnUrl%253D%25252FAccount%25252FLogin%25253FReturnUrl%25253D%……"
Any help would be appreciated.
Thanks.
2
Answers
You can add the code in the components that you want to keep from users not authenticated.
The _Imports.razor is not used like that. It allows you to define a set of namespaces that you want to import globally, making those namespaces available to all components within your application without explicitly importing them in each component.
Which means you can add the code in this way, the same effect.
1.Add in _Imports.razor.
2.Add in components you want to limit accessibility.
The @attribute [Authorize] tag is to label a page/component that you need to be authenticated in order to view the content, however this will not redirect you to the login page if you are not logged in and does not work in the _imports.
So if I understand you correctly you would like to redirect the users to auth before they get to the page with the @attribute [Authorize] attribute.
You can achieve this by adding a check to your "MainLayout.razor"
Here is an example of the a code behind: