Windows Authentication & Authorization in Blazor Application

In this article, we will explore windows authentication in Blazor so follow the below steps along with me,

Note -: I recommend you check out the previous article on the blazor series.

Step 1) Install the required NuGet package required for authorization

Right click on project-> Manage NuGet packages -> Search for Microsoft.AspNetCore.Components.Authorization -> install

NuGet Installation

Step 2) Make the required changes in ConfigureServices in Startup.cs class

Add services.AddAuthorizationCore() which will add all the necessary authorization services required for authorization to work in blazor application.

public void ConfigureServices(IServiceCollection services)

Step 3) In order to access everything inside a NuGet package define it in import.razor

@using System.Net.Http

Step 4) Defining AuthenticationStateProvider class

AuthenticationStateProvider as the name implies it is used to authenticate the user in blazor web application besides that it will define claims in class which contains other information about the authenticated user.

As you see in the below code we are getting windows user name after that fetching the role for that user and then creating a new authentication state with claims.

using EmployeeManagement.Web.Services;

Step 5) Restricting the navbar items as per role

In the NavMenu component, you need to add AuthorizeView with the role and Authorized attribute in each of component,

<div class=”top-row pl-4 navbar navbar-dark”>

As a result, you can see admin only able to see Home and AddUser tabs,

Step 6) Protecting component in blazor

As we have seen earlier Admin will able to see Home and Add Users tab but when we put route of dashboard page we are allowed to access because the component is not protected as you can see below,

To protect the component we need to add below code in individual component,

@page “/dashboard”

Once you added the required attributed you will see the message of Not authorized as below,

Thank You, See you in the next article !!

You can reach out or connect to me over here,

LinkedIn: https://www.linkedin.com/in/vaibhav-bhapkar

Email: vaibhavbhapkar.medium@gmail.com

If you want some technical topics to be discussed with group of participants please raise a request on following link: http://myblogsenquiry.somee.com/

Technical Speaker | Computer Engineer | Full Stack Web Developer | ML Enthusiast | * Knowledge Shared = Knowledge² *