Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Require authorization on ALL Blazor pages

I am playing with Blazor and created a web app that is server hosted. I have to put an authorize line on top of the page like this @attribute [Authorize] to ensure the user is logged in.

It seems like I have to add this line to each page individually. Is there a global setting that protects ALL the pages in the app, except for the login page of course.

Thanks!

like image 692
Franky Avatar asked Mar 14 '20 22:03

Franky


People also ask

How do I add authentication to Blazor WebAssembly?

To create a new Blazor WebAssembly project with an authentication mechanism: After choosing the Blazor WebAssembly App template in the Create a new ASP.NET Core Web Application dialog, select Change under Authentication. Select Individual User Accounts to use ASP.NET Core's Identity system.

What is CascadingAuthenticationState?

CascadingAuthenticationState Component It's responsible for providing the current authentication state to it's decendent components. Currently this value is used by the Router and AuthorizeView components to control access to various parts of the UI.


1 Answers

I believe that will work... Place the following code snippet in the _Imports.razor file

@using Microsoft.AspNetCore.Authorization
@attribute [Authorize]

In that case, when the Index page is hit, the user will be redirected to the Login page. If you want to perform authentication before the Blazor App is being render, add the code snippet from above in the _Host.cshtml file

Add the @attribute [AllowAnonymous] to specific pages you want to exculde from authentication, as for instance, the Index page.

like image 185
enet Avatar answered Oct 03 '22 05:10

enet