(24/30) Let's Learn Blazor Together: Using <AuthorizeRouteView>

(24/30) Let's Learn Blazor Together: Using <AuthorizeRouteView>

The day before yesterday, we added content in `Blog.razor` to display both authorized and unauthorized views. However, if the unauthorized content to be displayed is the same across the system, writing it in every component would be a waste of time. We can use `App.razor` to handle unified presentation.

Last updated 12/23/2021 10:51 PM
StrayaWorker
2 min read
Category
Blazor
Topic
Let's Learn Blazor Series
Tags
.NET C# ASP.NET Core Blazor

The day before yesterday, I added display content for both authenticated and unauthenticated users in Blog.razor. However, if the unauthenticated content to be displayed is the same across the system, writing it in every Component is a waste of time. We can use App.razor to handle this unified presentation.

First, delete the <AuthorizeView> that originally wrapped the content in Blog.razor, cut the <NotAuthorized> section, and add the line @attribute [Authorize] to inform Blazor that this Component requires authentication.

Then, change the single tag in App.razor to paired tags, paste the previously cut <NotAuthorized>, and restart the website. The content seen by unauthenticated users will be the same.

Currently, any authenticated user can see the same Component, but most systems usually have roles or permission divisions to distinguish different users. Tomorrow, we will try to use Role to differentiate authorization.

Note: The code in this article has been refactored using .NET 6 + Visual Studio 2022. You can click the original link to compare with the refactored code. Thank you for reading and supporting the original author.

Keep Exploring

Related Reading

More Articles
Same category / Same tag 12/25/2021

(29/30)Learn Blazor Together: Blazor Unit Testing

The most boring part of developing a system is probably fixing bugs, especially errors like trying to access a null object (`Object reference not set to an instance of an object.`), which is the most common problem most people encounter when they first step into programming. To break free from the tedious bug-fixing process, this article introduces `unit testing`.

Continue Reading
Same category / Same tag 12/25/2021

(28/30) Learning Blazor Together: Policy-based Authorization

It was mentioned earlier that `ASP.NET Core Identity` uses `Claim`-based authentication. In fact, `ASP.NET Core Identity` has different types of authorization methods, the simplest being `Login Authorization`, `Role Authorization`, and `Claim Authorization`. However, all of the above are implemented in one way: Policy-based Authorization.

Continue Reading