Windows Authentication & Authorization in Blazor Application

Vaibhav Bhapkar
4 min readAug 29, 2020

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){services.AddRazorPages();services.AddServerSideBlazor();services.AddHttpClient<IProductService, ProductService>(client =>{client.BaseAddress = new Uri(“https://localhost:44340/");});services.AddAuthorizationCore();}

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

@using System.Net.Http@using Microsoft.AspNetCore.Authorization@using Microsoft.AspNetCore.Components.Authorization@using Microsoft.AspNetCore.Components.Forms@using Microsoft.AspNetCore.Components.Routing@using Microsoft.AspNetCore.Components.Web@using Microsoft.JSInterop@using EmployeeManagement.Web@using EmployeeManagement.Web.Shared

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;using Microsoft.AspNetCore.Components.Authorization;using System;using System.Collections.Generic;using System.Linq;using System.Security.Claims;using System.Threading.Tasks;namespace EmployeeManagement.Web.Auth{public class WinAuthStateProvider : AuthenticationStateProvider{public async override Task<AuthenticationState> GetAuthenticationStateAsync(){//Getting logged in windows user namevar user = System.Security.Principal.WindowsIdentity.GetCurrent().Name;//Logic for fetching role from DB — Here you can get other details abou user from DB alsostring role = UserService.retRole(user.Split(‘\\’)[1]);//Generating new Authentication state with claims if user have any roleif (role != “” && role !=null){var WindowsAuth = new ClaimsIdentity(new List<Claim>() {new Claim(ClaimTypes.Name,user.Split(‘\\’)[1]),new Claim(ClaimTypes.Role,role)},”windows”);return await Task.FromResult(new AuthenticationState(new ClaimsPrincipal(WindowsAuth)));}else{var anonymous = new ClaimsIdentity();return await Task.FromResult(new AuthenticationState(new ClaimsPrincipal(anonymous)));}}}}

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”><a class=”navbar-brand” href=””>EmployeeManagement.Web</a><button class=”navbar-toggler” @onclick=”ToggleNavMenu”><span class=”navbar-toggler-icon”></span></button></div><div class=”@NavMenuCssClass” @onclick=”ToggleNavMenu”><ul class=”nav flex-column”><AuthorizeView Roles=”Admin”><Authorized><li class=”nav-item px-3"><NavLink class=”nav-link” href=”” Match=”NavLinkMatch.All”><span class=”oi oi-home” aria-hidden=”true”></span> Home</NavLink></li></Authorized></AuthorizeView><AuthorizeView Roles=”User”><Authorized><li class=”nav-item px-3"><NavLink class=”nav-link” href=”/dashboard” Match=”NavLinkMatch.All”><span class=”oi oi-home” aria-hidden=”true”></span> Dashboard</NavLink></li></Authorized></AuthorizeView><AuthorizeView Roles=”Admin”><Authorized><li class=”nav-item px-3"><NavLink class=”nav-link” href=”/addUser” Match=”NavLinkMatch.All”><span class=”oi oi-home” aria-hidden=”true”></span> Add Users</NavLink></li></Authorized></AuthorizeView></ul></div>@code {private bool collapseNavMenu = true;private string NavMenuCssClass => collapseNavMenu ? “collapse” : null;private void ToggleNavMenu(){collapseNavMenu = !collapseNavMenu;}}

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”@attribute [Authorize(Roles=”User”)]<h3>Dashboard</h3>@code {}

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/

--

--

Vaibhav Bhapkar

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