<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Varun on Medium]]></title>
        <description><![CDATA[Stories by Varun on Medium]]></description>
        <link>https://medium.com/@varu87?source=rss-479f0f0c03fa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Pir6ccAW0L1BSbQo0zRCJg.jpeg</url>
            <title>Stories by Varun on Medium</title>
            <link>https://medium.com/@varu87?source=rss-479f0f0c03fa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 15:57:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@varu87/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Authentication and Authorization in a Blazor Server app using Microsoft Entra ID and Microsoft…]]></title>
            <link>https://medium.com/@varu87/authentication-and-authorization-in-a-blazor-server-app-using-microsoft-entra-id-and-microsoft-3e9f5f32bd53?source=rss-479f0f0c03fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e9f5f32bd53</guid>
            <category><![CDATA[microsoft-graph]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[blazor-server]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[microsoft-entra-id]]></category>
            <dc:creator><![CDATA[Varun]]></dc:creator>
            <pubDate>Tue, 07 Nov 2023 03:51:52 GMT</pubDate>
            <atom:updated>2023-11-07T03:51:52.021Z</atom:updated>
            <content:encoded><![CDATA[<h3>Authentication and Authorization in a Blazor Server app using Microsoft Entra ID and Microsoft Graph</h3><p>In this article, let’s walk through the process of setting up authentication in a Blazor Server app using Microsoft Entra ID (formerly Azure Active Directory) and Microsoft Graph. The app will have</p><p>a) Public pages (accessible to all)</p><p>b) Private pages (accessible to authenticated users only)</p><p>c) Protected pages (accessible to users satisfying certain criteria)</p><h3>Prerequisites</h3><p>Before we begin, please make sure that the following prerequisites are in place:</p><ol><li>Latest version of <a href="https://dotnet.microsoft.com/en-us/download">dotnet</a>. (I am using dotnet 7).</li><li><a href="https://visualstudio.microsoft.com/downloads/">Visual Studio</a> or <a href="https://code.visualstudio.com/">Visual Studio Code</a> or any other IDE of your choice (I will be using Visual Studio 2022).</li><li>An <a href="https://portal.azure.com/">Azure account</a>.</li><li>A basic understanding of <a href="https://learn.microsoft.com/en-us/aspnet/core/blazor/hosting-models?view=aspnetcore-7.0#blazor-server">Blazor</a>.</li><li>Optional: A <a href="https://developer.microsoft.com/en-us/microsoft-365/dev-program">Microsoft 365 Developer Program Account</a>. This account provides a sandbox with sample data that can be used to emulate an actual organization.</li></ol><p><strong>Step 1: Create a Blazor Server app</strong></p><p>Let’s head over to Visual Studio and Create a new Project. We will scaffold the Blazor server app that gets created by default.</p><p><em>Please configure the app for HTTPS and do not set any authentication type for now, as we will set up authentication later.</em></p><p>Give an appropriate name to the project (I am calling the project <strong>BlazorAuthDemo</strong>).</p><p>When we run this application, it should bring up a demo blazor server app that has three pages: Home, Counter and Fetch Data. All these pages are accessible without authentication.</p><p><em>Please note the url at which the app is hosted. We will need this while setting up the app in Microsoft Entra ID</em></p><p><strong>Step 2: Create an app in Microsoft Entra ID</strong></p><p>Microsoft Entra ID (formerly Azure AD) is the OAuth service provided by Azure. Here’s the brief walkthrough of the steps to create an app in Microsoft Entra ID</p><ol><li>Log in to your <a href="https://portal.azure.com/">Azure portal</a> and select the tenant where you want to create the app.</li><li>Navigate to Microsoft Entra ID &gt; App Registrations and click the <em>New registration</em> button.</li><li>Give an appropriate name to the app and select a <em>Supported account type </em>based on your requirement. For this demo I will select <em>Accounts in this Organizational directory only.</em></li><li>Under <em>Redirect URI</em>, select <em>Web </em>as the application type and enter the URL of the locally hosted app that we built in the last step. It should end with signin-oidc, for e.g. if you app is hosted at <a href="https://localhost:5001/">https://localhost:5001</a> then the redirect URI should be <a href="https://localhost:5001/signin-oidc">https://localhost:5001/signin-oidc</a>.</li><li>Hit <em>Register </em>to create the app in Microsoft Entra ID.</li><li>Next go to the <em>Authentication</em> page and under <em>Implicit grant and hybrid flows, </em>where it says <em>Select the tokens you would like to be issued by the authorization endpoint, </em>select <em>ID tokens (used for implicit and hybrid flows)</em></li></ol><figure><img alt="Azure app settings" src="https://cdn-images-1.medium.com/max/1024/1*ktRXGiELzcWlfJVfkuGAEQ.png" /><figcaption>Azure app settings</figcaption></figure><p><em>Please note the Application (client) ID and the Directory (tenant) ID of the app.</em></p><p><strong>Step 3: Add authentication to the blazor app</strong></p><p><em>Before setting up the project, there is an optional step that I like to do for most of my dotnet projects. Head over to the .csproj file and disable ImplicitUsings and Nullable.</em></p><p><em>Once this is done, the build will fail and we will have to update the code so that the correct using statements are included in each class file.</em></p><p>Lets go back the blazor app we created in Step 1 and add the following nuget packages to the project.</p><p>a) Microsoft.Identity.Web</p><p>b) Microsoft.Identity.Web.UI</p><p>At the end of this step, the .csproj file should look as follows:</p><pre>&lt;Project Sdk=&quot;Microsoft.NET.Sdk.Web&quot;&gt;<br><br>  &lt;PropertyGroup&gt;<br>    &lt;TargetFramework&gt;net7.0&lt;/TargetFramework&gt;<br>    &lt;Nullable&gt;disable&lt;/Nullable&gt;<br>    &lt;ImplicitUsings&gt;disable&lt;/ImplicitUsings&gt;<br>  &lt;/PropertyGroup&gt;<br><br>  &lt;ItemGroup&gt;<br>    &lt;PackageReference Include=&quot;Microsoft.Identity.Web&quot; Version=&quot;2.15.3&quot; /&gt;<br>    &lt;PackageReference Include=&quot;Microsoft.Identity.Web.UI&quot; Version=&quot;2.15.3&quot; /&gt;<br>  &lt;/ItemGroup&gt;<br><br>&lt;/Project&gt;</pre><p>Next, we need to add the details of the Azure app we created in Step 2. Head over to the <strong>appsettings.json</strong> file and create a new section called <em>AzureAd </em>as follows:</p><pre>&quot;AzureAd&quot;: {<br>  &quot;Instance&quot;: &quot;https://login.microsoftonline.com/&quot;,<br>  &quot;TenantId&quot;: &quot;&lt;tenant id from step 2&gt;&quot;,<br>  &quot;ClientId&quot;: &quot;&lt;client id from step 2&gt;&quot;,<br>  &quot;CallbackPath&quot;: &quot;/signin-oidc&quot;<br>}</pre><p>Go to the <strong>program.cs</strong><em> </em>file and add update the file as below:</p><pre>using BlazorAuthDemo.Data;<br>using Microsoft.AspNetCore.Authentication.OpenIdConnect;<br>using Microsoft.AspNetCore.Builder;<br>using Microsoft.Extensions.DependencyInjection;<br>using Microsoft.Extensions.Hosting;<br>using Microsoft.Identity.Web;<br>using Microsoft.Identity.Web.UI;<br><br>namespace BlazorAuthDemo<br>{<br>    public class Program<br>    {<br>        public static void Main(string[] args)<br>        {<br>            var builder = WebApplication.CreateBuilder(args);<br><br>            builder.Services<br>                .AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)<br>                .AddMicrosoftIdentityWebApp(<br>                    builder.Configuration.GetSection(&quot;AzureAd&quot;));<br><br>            builder.Services<br>                .AddAuthorization(<br>                    policy =&gt; policy.FallbackPolicy = policy.DefaultPolicy);<br><br>            builder.Services.AddSingleton&lt;WeatherForecastService&gt;();<br>            builder.Services.AddRazorPages();<br><br>            builder.Services<br>                .AddServerSideBlazor()<br>                .AddMicrosoftIdentityConsentHandler();<br><br>            builder.Services<br>                .AddControllersWithViews()<br>                .AddMicrosoftIdentityUI();<br>            <br>            var app = builder.Build();<br><br>            if (!app.Environment.IsDevelopment())<br>            {<br>                app.UseExceptionHandler(&quot;/Error&quot;);<br>                app.UseHsts();<br>            }<br><br>            app.UseHttpsRedirection();<br>            app.UseStaticFiles();<br>            app.UseRouting();<br>            app.UseAuthentication();<br>            app.UseAuthorization();<br>            app.MapControllers();<br>            app.MapBlazorHub();<br>            app.MapFallbackToPage(&quot;/_Host&quot;);<br>            app.Run();<br>        }<br>    }<br>}</pre><p>Let’s walk through the code understanding the main parts</p><pre>builder.Services<br>   .AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)<br>   .AddMicrosoftIdentityWebApp(<br>       builder.Configuration.GetSection(&quot;AzureAd&quot;));</pre><p>This line configures the app to use Azure AD authentication. The <em>OpenIdConnectDefaults.AuthenticationScheme</em> is the default authentication scheme used by Azure AD. The <em>AddMicrosoftIdentityWebApp()</em> method adds the Azure AD authentication middleware to the app. The <em>GetSection(“AzureAd”)</em> method gets the Azure AD configuration settings from the appsettings.json file.</p><pre>builder.Services<br>   .AddAuthorization(<br>       policy =&gt; policy.FallbackPolicy = policy.DefaultPolicy);</pre><p>This line configures the app to use authorization. We have set the app to use the default authorization policy, that is the user must be authenticated to access the app.</p><pre>builder.Services<br>   .AddControllersWithViews()<br>   .AddMicrosoftIdentityUI();</pre><p>This line adds the Microsoft Identity UI pages to our app. It scaffolds the sign-in, sign-out pages for us.</p><p>If we run the app now, it should take us to <em>login.microsoftonline.com</em> by default. Once we login and give consent, we should be able to browse the app as normal.</p><p>If we wish to protect the entire app (without the need of public pages) this is the way to go. However, in order to have both public and private pages, we need to remove the following line from the program.cs file.</p><pre>builder.Services<br>    .AddAuthorization(<br>        policy =&gt; policy.FallbackPolicy = policy.DefaultPolicy);</pre><p>Now, all the pages should be accessible without the need for authentication.</p><p><strong>Step 4: Update project structure</strong></p><p>Now that we have added identity to the project, lets change the folder structure to segregate between the public and protected pages.</p><p>Under the project, create a new folder called <em>Views </em>and move the <em>Pages </em>and <em>Shared </em>folders into the newly created <em>Views </em>folder. At the end of this step, the folder structure should be as:</p><figure><img alt="Project structure after creating the Views folder" src="https://cdn-images-1.medium.com/max/353/1*0KvG03Jqduqam88xq74bUw.png" /><figcaption>Project structure after creating the Views folder</figcaption></figure><p>This will break the build. We need to go the _Imports.razor file in the root and locate the following line:</p><pre>@using BlazorAuthDemo.Shared</pre><p>This should be updated to</p><pre>@using BlazorAuthDemo.Views.Shared</pre><p>At the end of this step, the _Imports.razor file should like this</p><pre>@using System.Net.Http<br>@using Microsoft.AspNetCore.Authorization<br>@using Microsoft.AspNetCore.Components.Authorization<br>@using Microsoft.AspNetCore.Components.Forms<br>@using Microsoft.AspNetCore.Components.Routing<br>@using Microsoft.AspNetCore.Components.Web<br>@using Microsoft.AspNetCore.Components.Web.Virtualization<br>@using Microsoft.JSInterop<br>@using BlazorAuthDemo<br>@using BlazorAuthDemo.Views.Shared</pre><p>If we try to run the application now, we will get the following error</p><figure><img alt="Exception after changing the folder structure" src="https://cdn-images-1.medium.com/max/1024/1*WjgI6iSQnUU07fQurqFjEQ.png" /><figcaption>Exception after changing the folder structure</figcaption></figure><p>This happened because we moved the Pages folder from the root location to the Views folder. We need to add the following lines to the program.cs file to fix this issue.</p><pre>builder.Services<br>    .AddRazorPages(options =&gt; options.RootDirectory = &quot;/Views/Pages&quot;);</pre><p>At the end of this step, the program.cs file should like this:</p><pre>using BlazorAuthDemo.Data;<br>using Microsoft.AspNetCore.Authentication.OpenIdConnect;<br>using Microsoft.AspNetCore.Builder;<br>using Microsoft.Extensions.DependencyInjection;<br>using Microsoft.Extensions.Hosting;<br>using Microsoft.Identity.Web;<br>using Microsoft.Identity.Web.UI;<br><br>namespace BlazorAuthDemo<br>{<br>    public class Program<br>    {<br>        public static void Main(string[] args)<br>        {<br>            var builder = WebApplication.CreateBuilder(args);<br><br>            builder.Services<br>                .AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)<br>                .AddMicrosoftIdentityWebApp(<br>                    builder.Configuration.GetSection(&quot;AzureAd&quot;));<br><br>            builder.Services.AddSingleton&lt;WeatherForecastService&gt;();<br><br>            builder.Services<br>                .AddRazorPages(options =&gt;<br>                    options.RootDirectory = &quot;/Views/Pages&quot;);<br><br>            builder.Services<br>                .AddServerSideBlazor()<br>                .AddMicrosoftIdentityConsentHandler();<br><br>            builder.Services<br>                .AddControllersWithViews()<br>                .AddMicrosoftIdentityUI();<br>            <br>            var app = builder.Build();<br><br>            if (!app.Environment.IsDevelopment())<br>            {<br>                app.UseExceptionHandler(&quot;/Error&quot;);<br>                app.UseHsts();<br>            }<br><br>            app.UseHttpsRedirection();<br>            app.UseStaticFiles();<br>            app.UseRouting();<br>            app.UseAuthentication();<br>            app.UseAuthorization();<br>            app.MapControllers();<br>            app.MapBlazorHub();<br>            app.MapFallbackToPage(&quot;/_Host&quot;);<br>            app.Run();<br>        }<br>    }<br>}</pre><p>Running the project after making this change should load the app without any issues.</p><p>Now under the Pages folder, create a new folder called <em>Protected </em>and add an _Imports.razor file into it. All the pages that should be accessible only to authenticated users should be moved into this folder. I will move the <em>Counter.razor </em>and the <em>FetchData.razor </em>files here. At the end of this step, the folder structure should look as follows:</p><figure><img alt="Project structure after adding the Protected folder" src="https://cdn-images-1.medium.com/max/362/1*bRL2IdUjtWoFDzPRghsr4w.png" /><figcaption>Project structure after adding the Protected folder</figcaption></figure><p>The _Imports.razor is a special page in a blazor app that can be used to import namespaces and directives used by files within the same or children folders. We can use this to reduce boilerplate code.</p><p>In the _Imports.razor file (in the Protected folder) add the following code:</p><pre>@attribute [Authorize]</pre><p>This should add the Authorize attribute to all the pages within the Protected folder, so that we don’t have to add that directive on top of every class file in this folder (in this case, the <em>Counter </em>and <em>FetchData </em>pages).</p><p>However, if we try to run the app now, we will find that <em>Counter </em>and <em>FetchData </em>are still accessible without logging in. In order to fix this we need to add the <strong>AuthorizeRouteView </strong>in our app that tells blazor how to react to authorized and unauthorized user.</p><p>In the root of the project go to the App.razor file and change</p><pre>&lt;RouteView RouteData=&quot;@routeData&quot; DefaultLayout=&quot;@typeof(MainLayout)&quot; /&gt;</pre><p>to</p><pre>&lt;AuthorizeRouteView<br>    RouteData=&quot;@routeData&quot;<br>    DefaultLayout=&quot;@typeof(MainLayout)&quot; /&gt;</pre><p>Please wrap the entire app with <strong>CascadingAuthenticationState </strong>to ensure that the authentication state is available throughout. At the end of this step, the App.razor file should look like this:</p><pre>&lt;CascadingAuthenticationState&gt;<br>    &lt;Router AppAssembly=&quot;@typeof(App).Assembly&quot;&gt;<br>        &lt;Found Context=&quot;routeData&quot;&gt;<br>            &lt;AuthorizeRouteView<br>                RouteData=&quot;@routeData&quot;<br>                DefaultLayout=&quot;@typeof(MainLayout)&quot; /&gt;<br>            &lt;FocusOnNavigate RouteData=&quot;@routeData&quot; Selector=&quot;h1&quot; /&gt;<br>        &lt;/Found&gt;<br>        &lt;NotFound&gt;<br>            &lt;PageTitle&gt;Not found&lt;/PageTitle&gt;<br>            &lt;LayoutView Layout=&quot;@typeof(MainLayout)&quot;&gt;<br>                &lt;p role=&quot;alert&quot;&gt;Sorry, there&#39;s nothing at this address.&lt;/p&gt;<br>            &lt;/LayoutView&gt;<br>        &lt;/NotFound&gt;<br>    &lt;/Router&gt;<br>&lt;/CascadingAuthenticationState&gt;</pre><p>If we run the app now and go to either the /counter or /fetchdata route, we will see a <strong>Not Authorized </strong>message.</p><p><strong>Step 5: Redirect the user to Login page</strong></p><p>Instead of showing the Unauthorized message, let us redirect the users to the login page when they try to access a protected page.</p><p>Add another folder called Components under the Views folder and add a new razor component called <strong>RedirectToLogin</strong>. The folder structure should look like this at the end of this step:</p><figure><img alt="Project structure after adding the Components folder" src="https://cdn-images-1.medium.com/max/353/1*JISaTxLaR3SbOq_vuRwlTw.png" /><figcaption>Project structure after adding the Components folder</figcaption></figure><p>This is going to be a simple component that redirects the user to the login page. We will inject the <em>NavigationManager </em>that is shipped with blazor. Update the <strong>RedirectToLogin.razor.cs</strong> file as follows:</p><pre>using Microsoft.AspNetCore.Components;<br><br>namespace BlazorAuthDemo.Views.Components<br>{<br>    public partial class RedirectToLogin : ComponentBase<br>    {<br>        [Inject]<br>        protected NavigationManager NavigationManager { get; set; }<br><br>        protected override void OnInitialized()<br>        {<br>            NavigationManager.NavigateTo(&quot;MicrosoftIdentity/Account/SignIn&quot;);<br>        }<br>    }<br>}</pre><p>The <em>MicrosoftIdentity/Account/SignIn</em> page is a file that is automatically created for us by the <em>Microsoft.Identity.Web.UI</em> package.</p><p>Add the following code to <strong>RedirectToLogin.razor</strong> page:</p><pre>&lt;p&gt;Loading..&lt;/p&gt;</pre><p>If we run the app now and try navigating to the either the /counter or /fetchdata page by clicking on the left nav button, we will notice that the app goes to a page <em>https://&lt;localhost:port&gt;/MicrosoftIdentity/Account/SignIn </em>and displays a <em>message saying Sorry, there’s nothing at this address</em>.</p><figure><img alt="Redirect to login error" src="https://cdn-images-1.medium.com/max/831/1*I0HIZXH9G4WCoIFRW9T4fA.png" /><figcaption>Redirect to login error</figcaption></figure><p>This is because blazor implements client side routing by default, wherein it loads the content of the page and changes the url in the browser. Since, in this case, we want to load the page from the server, we need to update the code by setting the <em>forceLoad </em>option to true in the NavigateTo method.</p><p>Update the <strong>RedirectToLogin.razor.cs</strong> file as follows to fix this issue:</p><pre>using Microsoft.AspNetCore.Components;<br><br>namespace BlazorAuthDemo.Views.Components<br>{<br>    public partial class RedirectToLogin : ComponentBase<br>    {<br>        [Inject]<br>        protected NavigationManager NavigationManager { get; set; }<br><br>        protected override void OnInitialized()<br>        {<br>            NavigationManager.NavigateTo(<br>                uri: &quot;MicrosoftIdentity/Account/SignIn&quot;,<br>                forceLoad: true);<br>        }<br>    }<br>}</pre><p>Another issue with this implementation is that after login we will always go back to the home page. To prevent this we need to add the return url as a query string to SignIn page as follows:</p><pre>using Microsoft.AspNetCore.Components;<br><br>namespace BlazorAuthDemo.Views.Components<br>{<br>    public partial class RedirectToLogin : ComponentBase<br>    {<br>        [Inject]<br>        protected NavigationManager NavigationManager { get; set; }<br><br>        protected override void OnInitialized()<br>        {<br>            string returnUri = NavigationManager<br>                .ToBaseRelativePath(NavigationManager.Uri);<br><br>            string redirectUri =<br>                string.IsNullOrWhiteSpace(returnUri) ?<br>                    string.Empty : $&quot;?redirectUri=/{returnUri}&quot;;<br><br>            NavigationManager.NavigateTo(<br>                uri: $&quot;MicrosoftIdentity/Account/SignIn{redirectUri}&quot;,<br>                forceLoad: true);<br>        }<br>    }<br>}</pre><p>Now the app should redirect back to the page that triggered the authentication flow, after a successful login.</p><p><strong>Step 6: Add sign in and sign out functionality</strong></p><p>Ideally the app should have a sign in and sign out button with the nav menu showing and hiding links based on the user’s authentication state. We can use <strong>AuthorizeView </strong>to achieve this functionality.</p><p>Open the <strong>NavMenu.razor</strong> file present under Views &gt; Shared and wrap the <em>Counter </em>and <em>FetchData </em>link with the AuthorizeView tag as follows:</p><pre>&lt;AuthorizeView&gt;<br>    &lt;div class=&quot;nav-item px-3&quot;&gt;<br>        &lt;NavLink class=&quot;nav-link&quot; href=&quot;counter&quot;&gt;<br>            &lt;span class=&quot;oi oi-plus&quot; aria-hidden=&quot;true&quot; /&gt;<br>            Counter<br>        &lt;/NavLink&gt;<br>    &lt;/div&gt;<br>    &lt;div class=&quot;nav-item px-3&quot;&gt;<br>        &lt;NavLink class=&quot;nav-link&quot; href=&quot;fetchdata&quot;&gt;<br>            &lt;span class=&quot;oi oi-list-rich&quot; aria-hidden=&quot;true&quot; /&gt;<br>            Fetch data<br>        &lt;/NavLink&gt;<br>    &lt;/div&gt;<br>&lt;/AuthorizeView&gt;</pre><p>At the end of this step, the <strong>NavMenu.razor </strong>file should like this:</p><pre>&lt;div class=&quot;top-row ps-3 navbar navbar-dark&quot;&gt;<br>    &lt;div class=&quot;container-fluid&quot;&gt;<br>        &lt;a class=&quot;navbar-brand&quot; href=&quot;&quot;&gt;BlazorAuthDemo&lt;/a&gt;<br>        &lt;button<br>            title=&quot;Navigation menu&quot;<br>            class=&quot;navbar-toggler&quot;<br>            @onclick=&quot;ToggleNavMenu&quot;&gt;<br>            &lt;span class=&quot;navbar-toggler-icon&quot; /&gt;<br>        &lt;/button&gt;<br>    &lt;/div&gt;<br>&lt;/div&gt;<br><br>&lt;div<br>    class=&quot;@NavMenuCssClass nav-scrollable&quot;<br>    @onclick=&quot;ToggleNavMenu&quot;&gt;<br>    &lt;nav class=&quot;flex-column&quot;&gt;<br>        &lt;div class=&quot;nav-item px-3&quot;&gt;<br>            &lt;NavLink class=&quot;nav-link&quot; href=&quot;&quot; Match=&quot;NavLinkMatch.All&quot;&gt;<br>                &lt;span class=&quot;oi oi-home&quot; aria-hidden=&quot;true&quot; /&gt;<br>                Home<br>            &lt;/NavLink&gt;<br>        &lt;/div&gt;<br>        &lt;AuthorizeView&gt;<br>            &lt;div class=&quot;nav-item px-3&quot;&gt;<br>                &lt;NavLink class=&quot;nav-link&quot; href=&quot;counter&quot;&gt;<br>                    &lt;span class=&quot;oi oi-plus&quot; aria-hidden=&quot;true&quot; /&gt;<br>                    Counter<br>                &lt;/NavLink&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;nav-item px-3&quot;&gt;<br>                &lt;NavLink class=&quot;nav-link&quot; href=&quot;fetchdata&quot;&gt;<br>                    &lt;span class=&quot;oi oi-list-rich&quot; aria-hidden=&quot;true&quot; /&gt;<br>                    Fetch data<br>                &lt;/NavLink&gt;<br>            &lt;/div&gt;<br>        &lt;/AuthorizeView&gt;<br>    &lt;/nav&gt;<br>&lt;/div&gt;</pre><p>This will hide the <em>Counter </em>and <em>Fetch Data </em>links from the left nav by default and only show it to users who are logged.</p><p>We also need to give the users the option to log in and log out of the app. Blazor provides an <strong>AuthenticationStateProvider </strong>to track a user’s login state and identity that can be used to achieve this functionality.</p><p>Under Views &gt; Shared add a class file called <strong>MainLayout.razor.cs</strong> and add the following code to it:</p><pre>using Microsoft.AspNetCore.Components;<br>using Microsoft.AspNetCore.Components.Authorization;<br>using System.Security.Claims;<br>using System.Threading.Tasks;<br><br>namespace BlazorAuthDemo.Views.Shared<br>{<br>    public partial class MainLayout<br>    {<br>        [Inject]<br>        protected AuthenticationStateProvider Provider { get; set; }<br><br>        private string username;<br><br>        protected override async Task OnInitializedAsync()<br>        {<br>            AuthenticationState authenticationState =<br>                await Provider.GetAuthenticationStateAsync();<br><br>            ClaimsPrincipal user = authenticationState.User;<br>            username = user.Identity.Name;<br>        }<br>    }<br>}</pre><p>And update the MainLayout.razor file as follows:</p><pre>@inherits LayoutComponentBase<br><br>&lt;PageTitle&gt;BlazorAuthDemo&lt;/PageTitle&gt;<br><br>&lt;div class=&quot;page&quot;&gt;<br>    &lt;div class=&quot;sidebar&quot;&gt;<br>        &lt;NavMenu /&gt;<br>    &lt;/div&gt;<br><br>    &lt;main&gt;<br>        &lt;div class=&quot;top-row px-4&quot;&gt;<br>            &lt;AuthorizeView&gt;<br>                &lt;Authorized&gt;<br>                    Hello, @username<br>                    &lt;a href=&quot;MicrosoftIdentity/Account/SignOut&quot;&gt;Log out&lt;/a&gt;<br>                &lt;/Authorized&gt;<br>                &lt;NotAuthorized&gt;<br>                    &lt;a href=&quot;MicrosoftIdentity/Account/SignIn&quot;&gt;Log in&lt;/a&gt;<br>                &lt;/NotAuthorized&gt;<br>            &lt;/AuthorizeView&gt;<br>        &lt;/div&gt;<br><br>        &lt;article class=&quot;content px-4&quot;&gt;<br>            @Body<br>        &lt;/article&gt;<br>    &lt;/main&gt;<br>&lt;/div&gt;</pre><p>If we run the app now, we will see a <em>Log out </em>link next to the user name for an authenticated user. For every one else the app should show a <em>Log in </em>link. Similarly, the <em>Counter </em>and <em>FetchData </em>links should only be visible to logged in users.</p><p>Currently, when we log out from the application, we will be redirected to the <em>/MicrosoftIdentity/Account/SignedOut </em>route. In certain scenarios we may want the app to redirect to the home page instead. The easiest way to implement this is to add a <strong>UseRewriter </strong>middleware that looks for the SignedOut route and redirects the user to the home page.</p><p>Go to the program.cs file and update add the following line after the <strong>UseAuthorization </strong>middleware.</p><pre>app.UseRewriter(new RewriteOptions().Add(<br>    context =&gt;<br>    {<br>        if (context.HttpContext.Request.Path ==<br>                &quot;/MicrosoftIdentity/Account/SignedOut&quot;)<br>            context.HttpContext.Response.Redirect(&quot;/&quot;);<br>    }));</pre><p>The program.cs file should now look like this:</p><pre>using BlazorAuthDemo.Data;<br>using Microsoft.AspNetCore.Authentication.OpenIdConnect;<br>using Microsoft.AspNetCore.Builder;<br>using Microsoft.AspNetCore.Rewrite;<br>using Microsoft.Extensions.DependencyInjection;<br>using Microsoft.Extensions.Hosting;<br>using Microsoft.Identity.Web;<br>using Microsoft.Identity.Web.UI;<br><br>namespace BlazorAuthDemo<br>{<br>    public class Program<br>    {<br>        public static void Main(string[] args)<br>        {<br>            var builder = WebApplication.CreateBuilder(args);<br><br>            builder.Services<br>                .AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)<br>                .AddMicrosoftIdentityWebApp(<br>                    builder.Configuration.GetSection(&quot;AzureAd&quot;));<br><br>            builder.Services<br>                .AddControllersWithViews()<br>                .AddMicrosoftIdentityUI();<br><br>            builder.Services<br>                .AddRazorPages(options =&gt;<br>                    options.RootDirectory = &quot;/Views/Pages&quot;);<br><br>            builder.Services<br>                .AddServerSideBlazor()<br>                .AddMicrosoftIdentityConsentHandler();<br><br>            builder.Services.AddSingleton&lt;WeatherForecastService&gt;();<br><br>            var app = builder.Build();<br><br>            if (!app.Environment.IsDevelopment())<br>            {<br>                app.UseExceptionHandler(&quot;/Error&quot;);<br>                app.UseHsts();<br>            }<br><br>            app.UseHttpsRedirection();<br>            app.UseStaticFiles();<br>            app.UseRouting();<br>            app.UseAuthentication();<br>            app.UseAuthorization();<br><br>            app.UseRewriter(new RewriteOptions().Add(<br>                context =&gt;<br>                {<br>                    if (context.HttpContext.Request.Path ==<br>                            &quot;/MicrosoftIdentity/Account/SignedOut&quot;)<br>                        context.HttpContext.Response.Redirect(&quot;/&quot;);<br>                }));<br><br>            app.MapControllers();<br>            app.MapBlazorHub();<br>            app.MapFallbackToPage(&quot;/_Host&quot;);<br>            app.Run();<br>        }<br>    }<br>}</pre><p><strong>Step 7: Brief overview of Microsoft Graph</strong></p><p><a href="https://learn.microsoft.com/en-us/graph/overview"><strong>Microsoft Graph</strong></a> is a RESTful API that provides us with a set of endpoints that can be used to access user data from Microsoft 365. We will use this to get the logged in user’s name, email and security groups.</p><p>First let’s explore the Graph API using the <a href="https://developer.microsoft.com/en-us/graph/graph-explorer">Microsoft Graph Explorer</a>. Login to the Graph Explorer and send a GET request to the <a href="https://graph.microsoft.com/v1.0/me?$select=displayName,mail"><em>https://graph.microsoft.com/v1.0/me</em></a><em> </em>endpoint.</p><p><em>Please ensure that User.Read permission has been granted under the Modify Permissions tab.</em></p><figure><img alt="Microsoft Graph me endpoint" src="https://cdn-images-1.medium.com/max/1024/1*dAmQGZ-esy3WCmvANqZuVA.png" /><figcaption>Microsoft Graph me endpoint</figcaption></figure><p>This endpoint should return a set of user data including display name, email, job title etc. Since we only need the display name and email, we can overcome this <strong>over-fetching</strong> issue by passing the required fields in the query string. This is possible because the Graph API implements the <a href="https://www.odata.org/">OData</a> protocol.</p><p>Update the endpoint address to <a href="https://graph.microsoft.com/v1.0/me?$select=displayName,mail"><em>https://graph.microsoft.com/v1.0/me?$select=displayName,mail</em></a> and try running the query. We should notice that the result only contains the display name and email now.</p><figure><img alt="Microsoft Graph me endpoint returning only the display name and email" src="https://cdn-images-1.medium.com/max/1024/1*_xYT4aWxZVUHYHlHTdQcgg.png" /><figcaption>Microsoft Graph me endpoint returning only the display name and email</figcaption></figure><p>In order to retrieve the user’s security groups, we need to send a GET request to the <a href="https://graph.microsoft.com/v1.0/me/memberOf"><em>https://graph.microsoft.com/v1.0/me/memberOf</em></a> endpoint.</p><p><em>Before sending this request, please ensure that the Directory.Read.All permission has been granted This option should be available under the ModifyPermissions tab.</em></p><figure><img alt="Microsoft Graph security group endpoint" src="https://cdn-images-1.medium.com/max/1024/1*g8wUedzZ3n0y1_aG30C_gw.png" /><figcaption>Microsoft Graph security group endpoint</figcaption></figure><p>The response will be an array of security groups that the current user is a member of. Update the endpoint address to <a href="https://graph.microsoft.com/v1.0/me/memberOf?$select=displayName"><em>https://graph.microsoft.com/v1.0/me/memberOf?$select=displayName</em></a> to only return the group names.</p><figure><img alt="Microsoft Graph security group endpoint returning the display name only" src="https://cdn-images-1.medium.com/max/1024/1*p8RmMn-KoEBX3qPeRUokeg.png" /><figcaption>Microsoft Graph security group endpoint returning the display name only</figcaption></figure><p>Another powerful feature of Microsoft Graph (and OData) is its ability to process requests in batch. This means, that instead of sending two separate requests, one for the user details and another for the the user’s security group, we can combine the two and send it together, hence fixing the <strong>under-fetching</strong> issue.</p><p>Please send a POST request to the <a href="https://graph.microsoft.com/v1.0/$batch"><em>https://graph.microsoft.com/v1.0/$batch</em></a><em> </em>endpoint with the following request body:</p><figure><img alt="Batch request to the Graph endpoint" src="https://cdn-images-1.medium.com/max/1024/1*6RF5-ZmS6mYRMXAn8zD3qw.png" /><figcaption>Batch request to the Graph endpoint</figcaption></figure><pre>{<br>    &quot;requests&quot;: [<br>        {<br>            &quot;url&quot;: &quot;/me?$select=displayName,mail&quot;,<br>            &quot;method&quot;: &quot;GET&quot;,<br>            &quot;id&quot;: &quot;1&quot;<br>        },<br>        {<br>            &quot;url&quot;: &quot;/me/memberOf?$select=displayName&quot;,<br>            &quot;method&quot;: &quot;GET&quot;,<br>            &quot;id&quot;: &quot;2&quot;<br>        }<br>    ]<br>}</pre><p>Please take a note of the request and response structure as we will be using it to build Models in the next step. Each request can be defined by the following structure:</p><pre>{<br>    id: string,<br>    method: string,<br>    url: string<br>}</pre><p>And each response as follows:</p><pre>{<br>    id: string,<br>    status: int,<br>    headers: object,<br>    body: object<br>}</pre><p><strong>Step 8: Add authorization to the app</strong></p><p>Let’s login to the Azure portal and go to Microsoft Entra ID &gt; App registrations and select the app that was created in step 2.</p><p>From the left navigation, select API permissions and under the configured permissions, select Add a permission.</p><p>From the list of APIs in the slide in modal, select <strong>Microsoft Graph</strong>.</p><p>Select <em>Delegated permissions</em> for “<em>What type of permissions does your application require?</em>”</p><p>From the list of permissions, select <em>User.Read</em> and <em>Directory.Read.All</em>.</p><p>At the end of this step, the API permissions for the app should look like:</p><figure><img alt="Permissions for the registered Microsoft Entra ID app" src="https://cdn-images-1.medium.com/max/1024/1*oQsDnL5zQjkEaxcjzYICqA.png" /><figcaption>Permissions for the registered Microsoft Entra ID app</figcaption></figure><p>We also need to add a <em>client certificate</em> or <em>secret </em>to our app in Azure. This is required to prove the app’s identity by the downstream APIs when requesting a token.</p><p>Let’s go to the Certificates and secrets page for the app and create a new client secret. Please copy the value of this secret as we will require it in the next step.</p><p><em>If you have access to a certificate, please upload the same instead of using a client secret.</em></p><figure><img alt="Client secret of the app" src="https://cdn-images-1.medium.com/max/983/1*ROVLpyV74LFlTDz7VqZRvw.png" /><figcaption>Client secret of the app</figcaption></figure><p>Add the client secret or certificate information to the AzureAd section in the appsettings file. The appsettings file should now look like this:</p><pre>&quot;AzureAd&quot;: {<br>  &quot;Instance&quot;: &quot;https://login.microsoftonline.com/&quot;,<br>  &quot;TenantId&quot;: &quot;&lt;tenant id from step 2&gt;&quot;,<br>  &quot;ClientId&quot;: &quot;&lt;client id from step 2&gt;&quot;,<br>  &quot;CallbackPath&quot;: &quot;/signin-oidc&quot;,<br>  &quot;ClientSecret&quot;: &quot;&lt;client secret from last step&gt;&quot;,<br>  /*&quot;ClientCertificates&quot;: [<br>    {<br>      &quot;SourceType&quot;: &quot;&lt;client certificate source type&gt;&quot;,<br>      &quot;CertificateStorePath&quot;: &quot;&lt;client certificate store path&gt;&quot;,<br>      &quot;CertificateThumbprint&quot;: &quot;&lt;client certificate thumbprint&gt;&quot;<br>    }<br>  ]*/<br>}</pre><p>We also need to add the Microsoft Graph information to appsettings. Please add the following section to the file as follows:</p><pre>&quot;MicrosoftGraph&quot;: {<br>  &quot;BaseUrl&quot;: &quot;https://graph.microsoft.com/v1.0&quot;,<br>  &quot;Scopes&quot;: [ &quot;user.read&quot;, &quot;directory.read.all&quot; ]<br>}</pre><p>We will be using the <strong>Microsoft.Identity.Web.DownstreamApi</strong> library to call the downstream APIs taking care of the authentication details, including retrieving the token and adding it to the authorization header before calling the API.</p><p>Update the program.cs file as follows:</p><pre>using BlazorAuthDemo.Data;<br>using Microsoft.AspNetCore.Authentication.OpenIdConnect;<br>using Microsoft.AspNetCore.Builder;<br>using Microsoft.AspNetCore.Rewrite;<br>using Microsoft.Extensions.Configuration;<br>using Microsoft.Extensions.DependencyInjection;<br>using Microsoft.Extensions.Hosting;<br>using Microsoft.Identity.Web;<br>using Microsoft.Identity.Web.UI;<br><br>namespace BlazorAuthDemo<br>{<br>    public class Program<br>    {<br>        public static void Main(string[] args)<br>        {<br>            var builder = WebApplication.CreateBuilder(args);<br><br>            string[] initialScopes = builder<br>                .Configuration.GetSection(&quot;MicrosoftGraph:Scopes&quot;)?<br>                .Get&lt;List&lt;string&gt;&gt;()<br>                .ToArray();<br><br>            builder.Services<br>                .AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)<br>                .AddMicrosoftIdentityWebApp(<br>                    builder.Configuration.GetSection(&quot;AzureAd&quot;))<br>                .EnableTokenAcquisitionToCallDownstreamApi(initialScopes)<br>                .AddDownstreamApi(<br>                    &quot;MicrosoftGraph&quot;,<br>                    builder.Configuration.GetSection(&quot;MicrosoftGraph&quot;))<br>                .AddInMemoryTokenCaches();<br><br>            builder.Services<br>                .AddControllersWithViews()<br>                .AddMicrosoftIdentityUI();<br><br>            builder.Services<br>                .AddRazorPages(options =&gt;<br>                    options.RootDirectory = &quot;/Views/Pages&quot;);<br><br>            builder.Services<br>                .AddServerSideBlazor()<br>                .AddMicrosoftIdentityConsentHandler();<br><br>            builder.Services.AddSingleton&lt;WeatherForecastService&gt;();<br><br>            var app = builder.Build();<br><br>            if (!app.Environment.IsDevelopment())<br>            {<br>                app.UseExceptionHandler(&quot;/Error&quot;);<br>                app.UseHsts();<br>            }<br><br>            app.UseHttpsRedirection();<br>            app.UseStaticFiles();<br>            app.UseRouting();<br>            app.UseAuthentication();<br>            app.UseAuthorization();<br><br>            app.UseRewriter(new RewriteOptions().Add(<br>                context =&gt;<br>                {<br>                    if (context.HttpContext.Request.Path ==<br>                            &quot;/MicrosoftIdentity/Account/SignedOut&quot;)<br>                        context.HttpContext.Response.Redirect(&quot;/&quot;);<br>                }));<br><br>            app.MapControllers();<br>            app.MapBlazorHub();<br>            app.MapFallbackToPage(&quot;/_Host&quot;);<br>            app.Run();<br>        }<br>    }<br>}</pre><p>Next, let’s create a <em>Models </em>folder and add two sub folders — Requests and Responses. This will represent the request we send to the <em>ba</em>tch<em> </em>endpoint of the <em>Graph </em>API. In the Requests folder, add two classes — Request.cs and BatchRequest.cs, and under Responses, add Response.cs and BatchResponse.cs.</p><p>Let’s also add a <strong>User.cs, UserGroup.cs </strong>and <strong>UserGroupResponse.cs </strong>classes in the models folder which will represent the properties of the user.</p><figure><img alt="Folder structure after adding Models" src="https://cdn-images-1.medium.com/max/353/1*V4-RXyBfyfoKLw-nCkEwPw.png" /><figcaption>Folder structure after adding Models</figcaption></figure><p>Update the <strong>Request.cs</strong> file as follows:</p><pre>using System.Text.Json.Serialization;<br><br>namespace BlazorAuthDemo.Models.Requests<br>{<br>    public class Request<br>    {<br>        public string Id { get; set; }<br>        public string Method { get; set; }<br>        public string Url { get; set; }<br>    }<br><br>    public struct Method<br>    {<br>        public const string GET = &quot;GET&quot;;<br>        public const string POST = &quot;POST&quot;;<br>        public const string PUT = &quot;PUT&quot;;<br>        public const string DELETE = &quot;DELETE&quot;;<br>    }<br>}</pre><p><strong>BatchRequest.cs:</strong></p><pre>using System.Collections.Generic;<br><br>namespace BlazorAuthDemo.Models.Requests<br>{<br>    public class BatchRequest<br>    {<br>        public List&lt;Request&gt; Requests { get; set; }<br>    }<br>}</pre><p><strong>Response.cs:</strong></p><pre>namespace BlazorAuthDemo.Models.Responses<br>{<br>    public class Response<br>    {<br>        public string Id { get; set; }<br>        public int Status { get; set; }<br>        public object Headers { get; set; }<br>        public object Body { get; set; }<br>    }<br>}</pre><p><strong>BatchResponse.cs:</strong></p><pre>using System.Collections.Generic;<br><br>namespace BlazorAuthDemo.Models.Responses<br>{<br>    public class BatchResponse<br>    {<br>        public List&lt;Response&gt; Responses { get; set; }<br>    }<br>}</pre><p><strong>User.cs:</strong></p><pre>using System.Collections.Generic;<br><br>namespace BlazorAuthDemo.Models<br>{<br>    public class User<br>    {<br>        public string DisplayName { get; set; }<br>        public string Mail { get; set; }<br>        public List&lt;string&gt; Groups { get; set; }<br>    }<br>}</pre><p><strong>UserGroup.cs:</strong></p><pre>namespace BlazorAuthDemo.Models<br>{<br>    public class UserGroup<br>    {<br>        public string DisplayName { get; set; }<br>    }<br>}</pre><p><strong>UserGroupResponse.cs:</strong></p><pre>using System.Collections.Generic;<br><br>namespace BlazorAuthDemo.Models.Responses<br>{<br>    public class UserGroupResponse<br>    {<br>        public List&lt;UserGroup&gt; Value { get; set; }<br>    }<br>}</pre><p>Let’s add a razor component called <strong>AuthenticatedUser </strong>that contains the logged in user’s information. Every child of this component will have access to the user’s information.</p><p>Go to Views &gt; Components and a new razor component <strong>AuthenticatedUser.razor </strong>and <strong>AuthenticatedUser.razor.cs</strong></p><p><strong>AuthenticatedUser.razor.cs:</strong></p><pre>using BlazorAuthDemo.Models;<br>using BlazorAuthDemo.Models.Requests;<br>using BlazorAuthDemo.Models.Responses;<br>using Microsoft.AspNetCore.Components;<br>using Microsoft.Extensions.Logging;<br>using Microsoft.Identity.Abstractions;<br>using Microsoft.Identity.Web;<br>using System;<br>using System.Collections.Generic;<br>using System.Linq;<br>using System.Text.Json;<br>using System.Threading.Tasks;<br><br>namespace BlazorAuthDemo.Views.Components<br>{<br>    public partial class AuthenticatedUser<br>    {<br>        [Inject]<br>        public IDownstreamApi DownstreamApi { get; set; }<br><br>        [Inject]<br>        public ILogger&lt;AuthenticatedUser&gt; Logger { get; set; }<br><br>        [Inject]<br>        public MicrosoftIdentityConsentAndConditionalAccessHandler ConsentHandler { get; set; }<br><br>        [Parameter]<br>        public RenderFragment ChildContent { get; set; }<br><br>        public AuthenticatedUserComponentState State { get; set; }<br>        public User User { get; set; }<br><br>        private const string RequestIdForUserDetails = &quot;1&quot;;<br>        private const string RequestUrlForUserDetails =<br>            &quot;/me?$select=displayName,mail&quot;;<br><br>        private const string RequestIdForUserGroups = &quot;2&quot;;<br>        private const string RequestUrlForUserGroups = <br>            &quot;/me/memberOf?$select=displayName&quot;;<br><br>        protected async override Task OnInitializedAsync()<br>        {<br>            try<br>            {<br>                this.State = AuthenticatedUserComponentState.Loading;<br>                var batchRequest = GenerateRequest();<br><br>                BatchResponse response =<br>                    await DownstreamApi<br>                        .PostForUserAsync&lt;BatchRequest, BatchResponse&gt;(<br>                            &quot;MicrosoftGraph&quot;,<br>                            batchRequest,<br>                            options =&gt; options.RelativePath = &quot;$batch&quot;);<br><br>                User = ExtractUserDataFromBatchResponse(response);<br>                User.Groups = ExtractUserGroupsFromBatchResponse(response);<br><br>                this.State = AuthenticatedUserComponentState.Content;<br>            }<br>            catch (MicrosoftIdentityWebChallengeUserException ex)<br>            {<br>                ConsentHandler.HandleException(ex);<br>            }<br>            catch (Exception exception)<br>            {<br>                Logger.LogError(exception.Message);<br>                this.State = AuthenticatedUserComponentState.Error;<br>            }<br>        }<br><br>        private static BatchRequest GenerateRequest()<br>        {<br>            return new BatchRequest<br>            {<br>                Requests = new List&lt;Request&gt;<br>                    {<br>                        new Request<br>                        {<br>                            Id = RequestIdForUserDetails,<br>                            Method = Method.GET,<br>                            Url = RequestUrlForUserDetails<br>                        },<br>                        new Request<br>                        {<br>                            Id = RequestIdForUserGroups,<br>                            Method = Method.GET,<br>                            Url = RequestUrlForUserGroups<br>                        }<br>                    }<br>            };<br>        }<br><br>        private static User ExtractUserDataFromBatchResponse(<br>            BatchResponse batchResponse)<br>        {<br>            User userData = null;<br><br>            object body = (batchResponse.Responses<br>                        .Where(response =&gt;<br>                                RequestIdForUserDetails.Equals(response.Id) &amp;&amp;<br>                                response.Status == 200)<br>                        .FirstOrDefault()?<br>                        .Body) ??<br>                        throw new Exception(<br>                            &quot;Error processing user data request in Graph API&quot;);<br><br>            userData =<br>                    JsonSerializer.Deserialize&lt;User&gt;(<br>                        body.ToString(),<br>                        new JsonSerializerOptions<br>                        {<br>                            PropertyNameCaseInsensitive = true<br>                        });<br><br>            return userData;<br>        }<br><br>        private static List&lt;string&gt; ExtractUserGroupsFromBatchResponse(<br>            BatchResponse batchResponse)<br>        {<br>            List&lt;string&gt; userGroups = null;<br><br>            object body = (batchResponse.Responses<br>                        .Where(response =&gt;<br>                                RequestIdForUserGroups.Equals(response.Id) &amp;&amp;<br>                                response.Status == 200)<br>                        .FirstOrDefault()?<br>                        .Body) ??<br>                        throw new Exception(<br>                            &quot;Error processing user groups request in Graph API&quot;);<br><br>            UserGroupResponse userGroupResponse =<br>                JsonSerializer.Deserialize&lt;UserGroupResponse&gt;(<br>                    body.ToString(),<br>                    new JsonSerializerOptions<br>                    {<br>                        PropertyNameCaseInsensitive = true<br>                    });<br><br>            userGroups = userGroupResponse.Value<br>                            .Select(group =&gt; group.DisplayName)<br>                            .ToList();<br><br>            return userGroups;<br>        }<br>    }<br><br>    public enum AuthenticatedUserComponentState<br>    {<br>        Loading,<br>        Content,<br>        Error<br>    }<br>}</pre><p><strong>AuthenticatedUser.razor:</strong></p><pre>@if(State == AuthenticatedUserComponentState.Loading)<br>{<br>    &lt;p&gt;Loading..&lt;/p&gt;<br>}<br>else if(State == AuthenticatedUserComponentState.Content)<br>{<br>    &lt;CascadingValue Value=&quot;@User&quot;&gt;<br>        @ChildContent<br>    &lt;/CascadingValue&gt;<br>}<br>else if(State == AuthenticatedUserComponentState.Error)<br>{<br>    &lt;p&gt;An error occurred&lt;/p&gt;<br>}</pre><p>We are injecting the <em>DownstreamApi </em>object into our component. This makes it easy to retrieve the auth token returned by Azure and automatically add it to the header of the API call to <strong>Microsoft Graph</strong>.</p><p>This component has three states: <em>Loading, Content </em>and <em>Error </em>depicting the three states the component can be.</p><p>We also pass the User object as a <em>CascadingValue </em>so that it available to all children components of this component.</p><p>To demonstrate this, let’s create<strong> LoginDisplay </strong>component in the following location:</p><figure><img alt="Folder structure after adding LoginDisplay component" src="https://cdn-images-1.medium.com/max/354/1*rDxfegoTL_k1HBTtsqMy5w.png" /><figcaption>Folder structure after adding LoginDisplay component</figcaption></figure><p><strong>LoginDisplay.razor.cs</strong></p><pre>using BlazorAuthDemo.Models;<br>using Microsoft.AspNetCore.Components;<br><br>namespace BlazorAuthDemo.Views.Components<br>{<br>    public partial class LoginDisplay<br>    {<br>        [CascadingParameter]<br>        public User User { get; set; }<br><br>        protected override void OnInitialized()<br>        {<br>            var user = User;<br>        }<br>    }<br>}</pre><p><strong>LoginDisplay.razor</strong></p><pre>&lt;label title=&quot;@User?.Mail&quot;&gt;<br>    Hello, @User?.DisplayName<br>&lt;/label&gt;<br>&lt;a href=&quot;MicrosoftIdentity/Account/SignOut&quot;&gt;Log out&lt;/a&gt;</pre><p>Next go to Views &gt; Shared &gt; MainLayout.razor file and update the code as follows:</p><pre>@using BlazorAuthDemo.Views.Components<br>@inherits LayoutComponentBase<br><br>&lt;PageTitle&gt;BlazorAuthDemo&lt;/PageTitle&gt;<br><br>&lt;div class=&quot;page&quot;&gt;<br>    &lt;div class=&quot;sidebar&quot;&gt;<br>        &lt;NavMenu /&gt;<br>    &lt;/div&gt;<br><br>    &lt;main&gt;<br>        &lt;div class=&quot;top-row px-4&quot;&gt;<br>            &lt;AuthorizeView&gt;<br>                &lt;Authorized&gt;<br>                    &lt;AuthenticatedUser&gt;<br>                        &lt;LoginDisplay /&gt;<br>                    &lt;/AuthenticatedUser&gt;<br>                &lt;/Authorized&gt;<br>                &lt;NotAuthorized&gt;<br>                    &lt;a href=&quot;MicrosoftIdentity/Account/SignIn&quot;&gt;Log in&lt;/a&gt;<br>                &lt;/NotAuthorized&gt;<br>            &lt;/AuthorizeView&gt;<br>        &lt;/div&gt;<br><br>        &lt;article class=&quot;content px-4&quot;&gt;<br>            @Body<br>        &lt;/article&gt;<br>    &lt;/main&gt;<br>&lt;/div&gt;</pre><p>We have replaced the user’s name in the main layout with the LoginDisplay component wrapped around the AuthenticatedUser component.</p><p>If we run the app now, after a successful login, the menu bar should display the user’s name returned by Microsoft Graph.</p><p>Since we want every protected page to have access to the user object, we can create a new layout page and add it to the _imports file in the protected folder.</p><figure><img alt="Folder structure after adding ProtectedPagesLayout" src="https://cdn-images-1.medium.com/max/355/1*r0ptkuflUwF1yLXzAXcSAw.png" /><figcaption>Folder structure after adding ProtectedPagesLayout</figcaption></figure><p>Add the following code to <strong>ProtectedPagesLayout.razor</strong> file:</p><pre>@using BlazorAuthDemo.Views.Components<br>@inherits LayoutComponentBase<br>@layout MainLayout<br><br>&lt;AuthenticatedUser&gt;<br>    @Body<br>&lt;/AuthenticatedUser&gt;</pre><p>In the <strong>_Imports.razor</strong> file in Views &gt; Pages &gt; Protected folder add the following code:</p><pre>@layout ProtectedPagesLayout</pre><p>Now every page in the Protected folder has access to the user object.</p><p><strong>Step 9: Implement group based authorization</strong></p><p>Using the <em>AuthenticatedUser </em>component, we can restrict certain parts of the app so that they can be accessed by user’s belonging to a certain security group only. For example, let’s say our app should have certain pages that should only be accessible to user’s belonging to the Global Administrator group.</p><p>To implement this, let’s create a new component called <strong>AuthorizedUser.razor</strong> as follows:</p><figure><img alt="Folder structure after adding AuthorizedUser" src="https://cdn-images-1.medium.com/max/351/1*YwgsCGXI7PIP4-JO2KHEwA.png" /><figcaption>Folder structure after adding AuthorizedUser</figcaption></figure><p><strong>AuthorizedUser.razor.cs</strong></p><pre>using BlazorAuthDemo.Models;<br>using Microsoft.AspNetCore.Components;<br>using Microsoft.Extensions.Logging;<br>using System;<br>using System.Linq;<br><br>namespace BlazorAuthDemo.Views.Components<br>{<br>    public partial class AuthorizedUser<br>    {<br>        [Inject]<br>        public ILogger&lt;AuthorizedUser&gt; Logger { get; set; }<br><br>        [CascadingParameter]<br>        public User User { get; set; }<br><br>        [Parameter]<br>        public string AuthorizedGroups { get; set; }<br><br>        [Parameter]<br>        public RenderFragment ChildContent { get; set; }<br><br>        public AuthorizedUserComponentState State { get; set; }<br><br>        protected override void OnInitialized()<br>        {<br>            try<br>            {<br>                this.State = AuthorizedUserComponentState.Loading;<br><br>                bool isAuthorized = User.Groups.Any(group =&gt; <br>                                        AuthorizedGroups.Split(&#39;,&#39;).ToList()<br>                                        .Select(group =&gt; group.Trim())<br>                                        .Contains(group));<br><br>                this.State = isAuthorized ?<br>                                AuthorizedUserComponentState.Content :<br>                                AuthorizedUserComponentState.Unauthorized;<br>            }<br>            catch (Exception exception)<br>            {<br>                Logger.LogError(exception.Message);<br>                this.State = AuthorizedUserComponentState.Error;<br>            }<br>        }<br>    }<br><br>    public enum AuthorizedUserComponentState<br>    {<br>        Loading,<br>        Content,<br>        Unauthorized,<br>        Error<br>    }<br>}</pre><p><strong>AuthorizedUser.razor:</strong></p><pre>@if (State == AuthorizedUserComponentState.Loading)<br>{<br>    &lt;p&gt;Loading..&lt;/p&gt;<br>}<br>else if (State == AuthorizedUserComponentState.Content)<br>{<br>    @ChildContent<br>}<br>else if (State == AuthorizedUserComponentState.Unauthorized)<br>{<br>    &lt;p&gt;Unauthorized&lt;/p&gt;<br>}<br>else if (State == AuthorizedUserComponentState.Error)<br>{<br>    &lt;p&gt;An error occurred&lt;/p&gt;<br>}</pre><p>The <em>AuthorizedUser </em>must be a child of <em>AuthenticatedUser </em>and will have access to the <em>User </em>object as a cascading parameter. Additionally, we will pass a comma separated list of authorized groups. Only the users belonging to these groups will have access to the child content of AuthorizedUser.</p><blockquote>Please note that this way of authorization can be a huge security hole if you have allowed access to “any” Microsoft account while registering the app in Azure. This is because a user in another tenant can have the same group name as the one in your tenant and since we are only checking if they are authenticated and if they belong to a certain group (name), some unintended user can gain access to our app. Please ensure that you implement the authorization logic according to your business need. This code is only a demo explaining how to implement authorization and should not be used as-is.</blockquote><p>Next, we shall create a new layout file under Views &gt; Shared called <strong>GlobalAdministratorPagesLayout.razor</strong></p><figure><img alt="Folder structure after adding GlobalAdministratorPagesLayout" src="https://cdn-images-1.medium.com/max/360/1*ToEW7WczSs2ULuAS-EKMQw.png" /><figcaption>Folder structure after adding GlobalAdministratorPagesLayout</figcaption></figure><p><strong>GlobalAdministratorPagesLayout.razor:</strong></p><pre>@using BlazorAuthDemo.Views.Components<br>@inherits LayoutComponentBase<br>@layout ProtectedPagesLayout<br><br>&lt;AuthorizedUser AuthorizedGroups=&quot;Global Administrator&quot;&gt;<br>    @Body<br>&lt;/AuthorizedUser&gt;</pre><p>This layout inherits from the <strong>ProtectedPagesLayout </strong>and will thus be enclosed by the <em>AuthenticatedUser </em>component. Only the users belonging to the <em>Global Administrator</em> group are authorized to access the pages inheriting from this layout.</p><p>We can now proceed to create the global administrator pages. Under Views &gt; Pages &gt; Protected, create a folder called <strong>Global Administrators</strong> and add an <strong>_Imports.razor</strong> file and move the <strong>FetchData.razor</strong> file into this folder as follows:</p><figure><img alt="Folder structure after adding the Global Administrator directory" src="https://cdn-images-1.medium.com/max/358/1*xDZp7cmf9neduaNhUGphKw.png" /><figcaption>Folder structure after adding the Global Administrator directory</figcaption></figure><p>Update the newly created <strong>_Imports.razor</strong> file as follows:</p><pre>@layout GlobalAdministratorPagesLayout</pre><p>If we run the app now and try going to the <em>/fetchdata </em>route, we will notice that only the users belonging to the <em>Global Administrator</em> group can view the page. Everyone else will be shown the Unauthorized message as follows:</p><figure><img alt="Unauthorized page access" src="https://cdn-images-1.medium.com/max/1024/1*sWO0012gEwEvsDHJiXjATA.png" /><figcaption>Unauthorized page access</figcaption></figure><p>Let us also update the side nav so that the Fetch Data link is only visible to users who are authorized.</p><p>Go to Views &gt; Shared &gt; <strong>NavMenu.razor</strong> and wrap the Fetch Data link with the <em>AuthorizedUser </em>component as follows:</p><pre>&lt;AuthenticatedUser&gt;<br>    &lt;AuthorizedUser AuthorizedGroups=&quot;Global Administrator&quot;&gt;<br>        &lt;div class=&quot;nav-item px-3&quot;&gt;<br>            &lt;NavLink class=&quot;nav-link&quot; href=&quot;fetchdata&quot;&gt;<br>                &lt;span class=&quot;oi oi-list-rich&quot; aria-hidden=&quot;true&quot; /&gt;<br>                Fetch data<br>            &lt;/NavLink&gt;<br>        &lt;/div&gt;<br>    &lt;/AuthorizedUser&gt;<br>&lt;/AuthenticatedUser&gt;</pre><p>After this update, the <strong>NavMenu.razor</strong> file should like this:</p><pre>@using BlazorAuthDemo.Views.Components<br>&lt;div class=&quot;top-row ps-3 navbar navbar-dark&quot;&gt;<br>    &lt;div class=&quot;container-fluid&quot;&gt;<br>        &lt;a class=&quot;navbar-brand&quot; href=&quot;&quot;&gt;BlazorAuthDemo&lt;/a&gt;<br>        &lt;button<br>            title=&quot;Navigation menu&quot;<br>            class=&quot;navbar-toggler&quot;<br>            @onclick=&quot;ToggleNavMenu&quot;&gt;<br>            &lt;span class=&quot;navbar-toggler-icon&quot; /&gt;<br>        &lt;/button&gt;<br>    &lt;/div&gt;<br>&lt;/div&gt;<br><br>&lt;div<br>    class=&quot;@NavMenuCssClass nav-scrollable&quot;<br>    @onclick=&quot;ToggleNavMenu&quot;&gt;<br>    &lt;nav class=&quot;flex-column&quot;&gt;<br>        &lt;div class=&quot;nav-item px-3&quot;&gt;<br>            &lt;NavLink class=&quot;nav-link&quot; href=&quot;&quot; Match=&quot;NavLinkMatch.All&quot;&gt;<br>                &lt;span class=&quot;oi oi-home&quot; aria-hidden=&quot;true&quot; /&gt;<br>                Home<br>            &lt;/NavLink&gt;<br>        &lt;/div&gt;<br>        &lt;AuthorizeView&gt;<br>            &lt;div class=&quot;nav-item px-3&quot;&gt;<br>                &lt;NavLink class=&quot;nav-link&quot; href=&quot;counter&quot;&gt;<br>                    &lt;span class=&quot;oi oi-plus&quot; aria-hidden=&quot;true&quot; /&gt;<br>                    Counter<br>                &lt;/NavLink&gt;<br>            &lt;/div&gt;<br>            &lt;AuthenticatedUser&gt;<br>                &lt;AuthorizedUser AuthorizedGroups=&quot;Global Administrator&quot;&gt;<br>                    &lt;div class=&quot;nav-item px-3&quot;&gt;<br>                        &lt;NavLink class=&quot;nav-link&quot; href=&quot;fetchdata&quot;&gt;<br>                            &lt;span class=&quot;oi oi-list-rich&quot; aria-hidden=&quot;true&quot; /&gt;<br>                            Fetch data<br>                        &lt;/NavLink&gt;<br>                    &lt;/div&gt;<br>                &lt;/AuthorizedUser&gt;<br>            &lt;/AuthenticatedUser&gt;<br>        &lt;/AuthorizeView&gt;<br>    &lt;/nav&gt;<br>&lt;/div&gt;</pre><p>We wrapped the Fetch Data link with the <em>AuthenticatedUser </em>and <em>AuthorizedUser </em>component authorizing only the Global Administrators. Running the app now, we see that the Fetch Data link is available only to the Global Administrators. However, for every one else it displays Unauthorized, which is not a desired result.</p><figure><img alt="Navbar with authorized view" src="https://cdn-images-1.medium.com/max/1024/1*bYDIr0poq5E6nAKKilsqRQ.png" /><figcaption>Navbar with authorized view</figcaption></figure><p>In order to fix this let’s add a <em>Verbose </em>parameter to the <em>AuthorizedUser </em>component such that it only displays the error message if this parameter is true.</p><pre>[Parameter]<br>public bool Verbose { get; set; } = true;</pre><p>The <strong>AuthorizedUser.razor.cs</strong> file should like this now:</p><pre>using BlazorAuthDemo.Models;<br>using Microsoft.AspNetCore.Components;<br>using Microsoft.Extensions.Logging;<br>using System;<br>using System.Linq;<br><br>namespace BlazorAuthDemo.Views.Components<br>{<br>    public partial class AuthorizedUser<br>    {<br>        [Inject]<br>        public ILogger&lt;AuthorizedUser&gt; Logger { get; set; }<br><br>        [CascadingParameter]<br>        public User User { get; set; }<br><br>        [Parameter]<br>        public string AuthorizedGroups { get; set; }<br><br>        [Parameter]<br>        public RenderFragment ChildContent { get; set; }<br><br>        [Parameter]<br>        public bool Verbose { get; set; } = true;<br><br>        public AuthorizedUserComponentState State { get; set; }<br><br>        protected override void OnInitialized()<br>        {<br>            try<br>            {<br>                this.State = AuthorizedUserComponentState.Loading;<br><br>                bool isAuthorized = User.Groups.Any(group =&gt; <br>                                        AuthorizedGroups.Split(&#39;,&#39;).ToList()<br>                                        .Select(group =&gt; group.Trim())<br>                                        .Contains(group));<br><br>                this.State = isAuthorized ?<br>                                AuthorizedUserComponentState.Content :<br>                                AuthorizedUserComponentState.Unauthorized;<br>            }<br>            catch (Exception exception)<br>            {<br>                Logger.LogError(exception.Message);<br>                this.State = AuthorizedUserComponentState.Error;<br>            }<br>        }<br>    }<br><br>    public enum AuthorizedUserComponentState<br>    {<br>        Loading,<br>        Content,<br>        Unauthorized,<br>        Error<br>    }<br>}</pre><p>And the <strong>AuthorizedUser.razor</strong> file should be updated to:</p><pre>@if (State == AuthorizedUserComponentState.Loading)<br>{<br>    &lt;p&gt;Loading..&lt;/p&gt;<br>}<br>else if (State == AuthorizedUserComponentState.Content)<br>{<br>    @ChildContent<br>}<br>else if (State == AuthorizedUserComponentState.Unauthorized &amp;&amp; Verbose)<br>{<br>    &lt;p&gt;Unauthorized&lt;/p&gt;<br>}<br>else if (State == AuthorizedUserComponentState.Error)<br>{<br>    &lt;p&gt;An error occurred&lt;/p&gt;<br>}</pre><p>Next, let’s update the NavMenu.razor file by setting the verbose parameter to false in the AuthorizedUser component:</p><pre>&lt;AuthorizedUser<br>    AuthorizedGroups=&quot;Global Administrator&quot;<br>    Verbose=false&gt;<br>    &lt;div class=&quot;nav-item px-3&quot;&gt;<br>        &lt;NavLink class=&quot;nav-link&quot; href=&quot;fetchdata&quot;&gt;<br>            &lt;span class=&quot;oi oi-list-rich&quot; aria-hidden=&quot;true&quot; /&gt;<br>            Fetch data<br>        &lt;/NavLink&gt;<br>    &lt;/div&gt;<br>&lt;/AuthorizedUser&gt;</pre><p>The NavMenu.razor file should look as follows:</p><pre>@using BlazorAuthDemo.Views.Components<br>&lt;div class=&quot;top-row ps-3 navbar navbar-dark&quot;&gt;<br>    &lt;div class=&quot;container-fluid&quot;&gt;<br>        &lt;a class=&quot;navbar-brand&quot; href=&quot;&quot;&gt;BlazorAuthDemo&lt;/a&gt;<br>        &lt;button<br>            title=&quot;Navigation menu&quot;<br>            class=&quot;navbar-toggler&quot;<br>            @onclick=&quot;ToggleNavMenu&quot;&gt;<br>            &lt;span class=&quot;navbar-toggler-icon&quot; /&gt;<br>        &lt;/button&gt;<br>    &lt;/div&gt;<br>&lt;/div&gt;<br><br>&lt;div<br>    class=&quot;@NavMenuCssClass nav-scrollable&quot;<br>    @onclick=&quot;ToggleNavMenu&quot;&gt;<br>    &lt;nav class=&quot;flex-column&quot;&gt;<br>        &lt;div class=&quot;nav-item px-3&quot;&gt;<br>            &lt;NavLink class=&quot;nav-link&quot; href=&quot;&quot; Match=&quot;NavLinkMatch.All&quot;&gt;<br>                &lt;span class=&quot;oi oi-home&quot; aria-hidden=&quot;true&quot; /&gt;<br>                Home<br>            &lt;/NavLink&gt;<br>        &lt;/div&gt;<br>        &lt;AuthorizeView&gt;<br>            &lt;div class=&quot;nav-item px-3&quot;&gt;<br>                &lt;NavLink class=&quot;nav-link&quot; href=&quot;counter&quot;&gt;<br>                    &lt;span class=&quot;oi oi-plus&quot; aria-hidden=&quot;true&quot; /&gt;<br>                    Counter<br>                &lt;/NavLink&gt;<br>            &lt;/div&gt;<br>            &lt;AuthenticatedUser&gt;<br>                &lt;AuthorizedUser<br>                    AuthorizedGroups=&quot;Global Administrator&quot;<br>                    Verbose=false&gt;<br>                    &lt;div class=&quot;nav-item px-3&quot;&gt;<br>                        &lt;NavLink class=&quot;nav-link&quot; href=&quot;fetchdata&quot;&gt;<br>                            &lt;span class=&quot;oi oi-list-rich&quot; aria-hidden=&quot;true&quot; /&gt;<br>                            Fetch data<br>                        &lt;/NavLink&gt;<br>                    &lt;/div&gt;<br>                &lt;/AuthorizedUser&gt;<br>            &lt;/AuthenticatedUser&gt;<br>        &lt;/AuthorizeView&gt;<br>    &lt;/nav&gt;<br>&lt;/div&gt;<br><br></pre><p>If we run the app now, the Fetch Data link should be hidden for users outside the Global Administrator group.</p><p>The source code for the app can be found at <a href="https://github.com/varu87/BlazorAuthDemo">https://github.com/varu87/BlazorAuthDemo</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e9f5f32bd53" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Azure AD Authentication in SvelteKit]]></title>
            <link>https://medium.com/@varu87/azure-ad-authentication-in-sveltekit-f596cfa8a349?source=rss-479f0f0c03fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/f596cfa8a349</guid>
            <dc:creator><![CDATA[Varun]]></dc:creator>
            <pubDate>Tue, 16 May 2023 01:36:44 GMT</pubDate>
            <atom:updated>2023-11-11T00:37:11.288Z</atom:updated>
            <content:encoded><![CDATA[<p>Do you need to add authentication to your SvelteKit app? One popular way to do this is to use Azure Active Directory (Azure AD), a cloud-based identity and access management service from Microsoft. With Azure AD, you can easily add user authentication to your app without having to manage user accounts and passwords yourself. In this guide, we’ll see how to create an app in Azure AD and implement Azure AD authentication in a SvelteKit app using the Authorization Code Flow.</p><p><strong>Step 1</strong>: <strong>Create an App in Azure Active Directory</strong></p><p>Before we can use Azure AD for authentication, we need to create an app in our Azure AD tenant. Here’s how to do it:</p><ol><li>Log in to the <a href="https://portal.azure.com/">Azure portal</a>.</li><li>Select your Azure AD tenant from the menu on the left.</li><li>Click on the “App registrations” menu item.</li><li>Click on the “New registration” button.</li><li>Give the app a name and choose the “Web” application type.</li><li>Enter the “Redirect URI” for the app. This is the URL where Azure AD will redirect the user after authentication. For example, if the app is hosted at http://localhost:5173, Redirect URI should be <a href="http://localhost:5173/callback">http://localhost:5173/callback</a>.</li><li>Click on the “Register” button.</li><li>Go to the “Certificates and Secrets” section of the app and create a new client secret by giving it a name and an expiration date.</li></ol><p>Congratulations! You’ve now created an app in Azure AD. Make a note of the “Application (client) ID”, the “Directory (tenant) ID” and the “Client Secret” value, as we’ll need these later.</p><p><strong>Step 2: Understanding the Authorization Code Flow</strong></p><p>Before we dive into the code, let’s take a moment to understand how the Authorization Code Flow works as defined by OAuth2. This is the flow that Azure AD uses for authentication.</p><p>The Authorization Code Flow consists of the following steps:</p><ol><li>The client (i.e. your app) redirects the user to the authorization server (i.e. Azure AD), along with some parameters, such as the client ID and the Redirect URI.</li><li>The user logs in to the authorization server and consents to the requested permissions.</li><li>The authorization server redirects the user back to the client app, along with an authorization code.</li><li>The client app exchanges the authorization code for an access token and a refresh token.</li><li>The client app uses the access token to access protected resources on behalf of the user.</li></ol><p><strong>Step 3: Create a Sveltekit App and Implement Azure AD Authentication</strong></p><p>Now that we understand the Authorization Code Flow, let’s create a SvelteKit app and implement Azure AD authentication. Here’s how to do it:</p><p><em>Before we start with creating a sveltekit app, please ensure that you have the latest version of </em><a href="https://nodejs.org/"><em>Node</em></a><em> installed in your system.</em></p><ol><li>Create a sveltekit app. We will use the Skeleton project as the starting point and use Typescript for type checking.</li></ol><pre>npm create svelte@latest sveltekit-aad-auth</pre><p>Once the app is created, cd into the project folder and install the dependencies.</p><pre>cd sveltekit-aad-auth<br>npm i</pre><p>Once done, open the project in your favorite text editor.</p><p>2. Update the project folder structure as follows:</p><p>a) Since sveltekit allows us to group layouts together, we will create folder named “(protected)” under routes and move the <em>+page.svelte </em>file into this folder. Only authenticated users can access the resources in (protected) folder.</p><p>b) We will also create a “callback” folder under routes and add a <em>+server.ts</em> file in it. This name should be the same as mentioned in the redirect URI while registering the Azure AD app.</p><p>c) Add a hooks.server.ts file under the src folder. In sveltekit, all server requests first go through the “handle” function defined in the hooks.server file. This is where we check if the user is requesting a protected resource and serve the page only if the said user is authenticated. Update the hooks.server.ts file with the following code:</p><pre>import type { Handle } from &quot;@sveltejs/kit&quot;;<br><br>export const handle: Handle = async ({ event, resolve }) =&gt; {<br>  return await resolve(event);<br>};</pre><p>At the end of this step, the folder structure should look like this</p><figure><img alt="Folder structure" src="https://cdn-images-1.medium.com/max/263/1*cZwcUhZdHxLOPxmhM_KxUQ.png" /><figcaption>Folder structure after step 2</figcaption></figure><p>3. Start the development server.</p><pre>npm run dev -- --open</pre><p>The application should open in your browser displaying the default page.</p><figure><img alt="Default page served by sveltekit" src="https://cdn-images-1.medium.com/max/523/1*CdDcllftOa-InkKmFGrMmA.png" /><figcaption>Default page served by sveltekit</figcaption></figure><p>If we were to go into the hooks.server.ts file and update the code as follows:</p><pre>import type { Handle } from &quot;@sveltejs/kit&quot;;<br><br>export const handle: Handle = async ({ event, resolve }) =&gt; {<br>  if (event.route.id &amp;&amp; event.route.id.indexOf(&quot;(protected)&quot;) &gt; 0) {<br>    return new Response(&quot;Authentication required&quot;);<br>  }<br>  return await resolve(event);<br>};</pre><p>the following page will be served:</p><figure><img alt="Page served after updating the hooks.server.ts file" src="https://cdn-images-1.medium.com/max/449/1*9_lvBttdb9X5M179s12BXw.png" /><figcaption>Page served after updating the hooks.server.ts file</figcaption></figure><p>We can now update this logic to send the user to Microsoft authentication page instead of displaying the “Authentication required” message.</p><p>4. Stop the development server and install the following dependency.</p><pre>npm i -D @azure/msal-node</pre><p>5. Create a .env file in the root of the project and update it with the following entries:</p><pre>CLOUD_INSTANCE=&quot;https://login.microsoftonline.com/&quot;<br>TENANT_ID=&lt;tenant id from step 1&gt;<br>CLIENT_ID=&lt;client id from step 1&gt;<br>CLIENT_SECRET=&lt;client secret from step 1&gt;<br>REDIRECT_URI=&lt;callback uri from step 1&gt;</pre><p>Next create a “lib” folder under “src”. Inside “lib” create another folder called “auth” with “config.ts” and “services.ts” files. After this step the folder structure should look like this:</p><figure><img alt="Folder structure after step 5" src="https://cdn-images-1.medium.com/max/267/1*0Rn-RHJW-9lJfJqZEkJ9ng.png" /><figcaption>Folder structure after step 5</figcaption></figure><p>6. Run the server again.</p><pre>npm run dev -- --open</pre><p>7. Update the <strong>lib &gt; auth &gt; config.ts</strong> as follows:</p><pre>import {<br>  CLIENT_ID,<br>  CLOUD_INSTANCE,<br>  TENANT_ID,<br>  CLIENT_SECRET,<br>} from &quot;$env/static/private&quot;;<br><br>export const msalConfig = {<br>  auth: {<br>    clientId: CLIENT_ID,<br>    authority: CLOUD_INSTANCE + TENANT_ID,<br>    clientSecret: CLIENT_SECRET,<br>  },<br>};</pre><p>8. As mentioned earlier, the first step in the Authorization code flow is redirecting the client to Microsoft’s authentication page. This is done by the <strong>getAuthCodeUrl </strong>method provided by the <strong>msal-node</strong> library.</p><p>In order to implement this, update the <strong>lib &gt; auth &gt; services.ts</strong> file with the following code:</p><pre>import type { RequestEvent } from &quot;@sveltejs/kit&quot;;<br>import {<br>  ConfidentialClientApplication,<br>  CryptoProvider,<br>  ResponseMode,<br>} from &quot;@azure/msal-node&quot;;<br>import { REDIRECT_URI } from &quot;$env/static/private&quot;;<br>import { dev } from &quot;$app/environment&quot;;<br>import { msalConfig } from &quot;./config&quot;;<br><br>const msalInstance = new ConfidentialClientApplication(msalConfig);<br>const cryptoProvider = new CryptoProvider();<br><br>export const redirectToAuthCodeUrl = async (event: RequestEvent) =&gt; {<br>  const { verifier, challenge } = await cryptoProvider.generatePkceCodes();<br>  const pkceCodes = {<br>    challengeMethod: &quot;S256&quot;,<br>    verifier,<br>    challenge,<br>  };<br><br>  const authCodeUrlRequest = {<br>    redirectUri: REDIRECT_URI,<br>    responseMode: ResponseMode.QUERY,<br>    codeChallenge: pkceCodes.challenge,<br>    codeChallengeMethod: pkceCodes.challengeMethod,<br>    scopes: [],<br>  };<br><br>  try {<br>    const authCodeUrl = await msalInstance.getAuthCodeUrl(authCodeUrlRequest);<br>    event.cookies.set(&quot;pkceVerifier&quot;, verifier, {<br>      httpOnly: true,<br>      path: &quot;/&quot;,<br>      secure: !dev,<br>    });<br>    return authCodeUrl;<br>  } catch (err) {<br>    console.log(err);<br>  }<br>};</pre><p>Azure AD uses Authorization Code flow with PKCE (proof key for code exchange). The <strong>CryptoProvider</strong> class in the msal-node library can be used to generate the pkce codes that are sent to Azure AD while authentication. Our app should verify that the same codes are sent back to us from Azure after the authentication has been successful.</p><p>Next go to the hooks.server.ts file and update the code as follows:</p><pre>import { redirect, type Handle } from &quot;@sveltejs/kit&quot;;<br>import { redirectToAuthCodeUrl } from &quot;$lib/auth/services&quot;;<br><br>export const handle: Handle = async ({ event, resolve }) =&gt; {<br>  if (event.route.id &amp;&amp; event.route.id.indexOf(&quot;(protected)&quot;) &gt; 0) {<br>    const authCodeUrl = await redirectToAuthCodeUrl(event);<br>    if (authCodeUrl) throw redirect(302, authCodeUrl);<br>  }<br>  return await resolve(event);<br>};</pre><p>Now if we go to <a href="http://localhost:5173,">http://localhost:5173,</a> the client should automatically redirect to <a href="https://login.microsoftonline.com/">https://login.microsoftonline.com/</a></p><p>The user will need to login and provide consent for our app to access their email and profile details.</p><p>Based on whether the authentication is successful or not, Azure will send a “code” or “error” in the query string of the redirect URL. It is up to us to interpret this response and serve the app accordingly.</p><p>9. Open the <strong>lib &gt; auth &gt; services.ts</strong> file and update the code as follows:</p><pre>import type { RequestEvent } from &quot;@sveltejs/kit&quot;;<br>import {<br>  ConfidentialClientApplication,<br>  CryptoProvider,<br>  ResponseMode,<br>} from &quot;@azure/msal-node&quot;;<br>import { REDIRECT_URI } from &quot;$env/static/private&quot;;<br>import { dev } from &quot;$app/environment&quot;;<br>import { msalConfig } from &quot;./config&quot;;<br><br>const msalInstance = new ConfidentialClientApplication(msalConfig);<br>const cryptoProvider = new CryptoProvider();<br><br>const cookiesConfig = {<br>  httpOnly: true,<br>  path: &quot;/&quot;,<br>  secure: !dev,<br>};<br><br>export const redirectToAuthCodeUrl = async (event: RequestEvent) =&gt; {<br>  const { verifier, challenge } = await cryptoProvider.generatePkceCodes();<br>  const pkceCodes = {<br>    challengeMethod: &quot;S256&quot;,<br>    verifier,<br>    challenge,<br>  };<br><br>  const authCodeUrlRequest = {<br>    redirectUri: REDIRECT_URI,<br>    responseMode: ResponseMode.QUERY,<br>    codeChallenge: pkceCodes.challenge,<br>    codeChallengeMethod: pkceCodes.challengeMethod,<br>    scopes: [],<br>  };<br><br>  try {<br>    const authCodeUrl = await msalInstance.getAuthCodeUrl(authCodeUrlRequest);<br>    event.cookies.set(&quot;pkceVerifier&quot;, verifier, cookiesConfig);<br>    return authCodeUrl;<br>  } catch (err) {<br>    console.log(err);<br>  }<br>};<br><br>export const getTokens = async (event: RequestEvent) =&gt; {<br>  const code = event.url.searchParams.get(&quot;code&quot;);<br>  const error = event.url.searchParams.get(&quot;error&quot;);<br>  if (code) {<br>    const authCodeRequest = {<br>      redirectUri: REDIRECT_URI,<br>      code,<br>      scopes: [],<br>      codeVerifier: event.cookies.get(&quot;pkceVerifier&quot;),<br>    };<br>    try {<br>      const tokenResponse = await msalInstance.acquireTokenByCode(<br>        authCodeRequest<br>      );<br>      event.cookies.set(<br>        &quot;accessToken&quot;,<br>        tokenResponse.accessToken,<br>        cookiesConfig<br>      );<br>      event.cookies.set(&quot;idToken&quot;, tokenResponse.idToken, cookiesConfig);<br>      event.cookies.set(<br>        &quot;account&quot;,<br>        JSON.stringify(tokenResponse.account),<br>        cookiesConfig<br>      );<br>      return &quot;/&quot;;<br>    } catch (err) {<br>      console.log(error);<br>      throw new Error(&quot;Error getting access tokens&quot;);<br>    }<br>  } else if (error) {<br>    throw new Error(error);<br>  } else {<br>    throw new Error(&quot;Invalid authentication request&quot;);<br>  }<br>};</pre><p>We add a <strong>getTokens</strong> method that accepts a request event as an input parameter. We can retrieve the query parameter from this event object to check if it returned a “code” or “error”. Passing the “code” and the “pkce verifier” (that was generated while getting the auth code url) to the <strong>acquireTokenByCode</strong> method will give us the access and id tokens. We can save these in a http only cookie for later use and send the user back to the home page as shown in the above code.</p><p>We then need to call the <strong>getToken</strong> method in the <strong>routes &gt; callback &gt; +server.ts</strong> file as follows:</p><pre>import { redirect } from &quot;@sveltejs/kit&quot;;<br>import type { RequestHandler } from &quot;./$types&quot;;<br>import { getTokens } from &quot;$lib/auth/services&quot;;<br><br>export const GET: RequestHandler = async (event) =&gt; {<br>  const redirectTo = await getTokens(event);<br>  throw redirect(302, redirectTo);<br>};</pre><p>Since the user is getting redirected to “/”, we need to update the hooks.server.ts file to redirect the users to the authentication server only if they are not already authenticated. Update the hooks.server.ts file as follows:</p><pre>import { redirect, type Handle } from &quot;@sveltejs/kit&quot;;<br>import { redirectToAuthCodeUrl } from &quot;$lib/auth/services&quot;;<br><br>export const handle: Handle = async ({ event, resolve }) =&gt; {<br>  if (event.route.id &amp;&amp; event.route.id.indexOf(&quot;(protected)&quot;) &gt; 0) {<br>    if (!event.cookies.get(&quot;idToken&quot;) || !event.cookies.get(&quot;accessToken&quot;)) {<br>      const authCodeUrl = await redirectToAuthCodeUrl(event);<br>      if (authCodeUrl) throw redirect(302, authCodeUrl);<br>    }<br>  }<br>  return await resolve(event);<br>};</pre><p>With this we have successfully authenticated the user, however there are a few enhancements we need to make in order to improve the user experience and protect the app against CSRF attacks.</p><p>At present, after the user is authenticated, we are always redirecting them to the “/” page, even if the user initiated the authentication from a different page. In order to prevent this, we are provided with a <strong>state</strong> parameter that can be used to tell the authentication server from which page the request was initiated. After completing the authentication process, the auth server returns the state parameter as is and can hence be used to redirect the user back to the resource that was initially requested.</p><p>The <strong>state</strong> parameter can also be used to determine that the response is actually coming from the authentication server and not from a malicious party by adding a unique nonce (or csrf token). We need to store this token in the server before sending the request to the authentication server and verify that the same token is returned after a successful login.</p><p>10. Update the <strong>lib &gt; auth &gt; services.ts</strong> file as follows:</p><pre>import type { RequestEvent } from &quot;@sveltejs/kit&quot;;<br>import {<br>  ConfidentialClientApplication,<br>  CryptoProvider,<br>  ResponseMode,<br>} from &quot;@azure/msal-node&quot;;<br>import { REDIRECT_URI } from &quot;$env/static/private&quot;;<br>import { dev } from &quot;$app/environment&quot;;<br>import { msalConfig } from &quot;./config&quot;;<br><br>const msalInstance = new ConfidentialClientApplication(msalConfig);<br>const cryptoProvider = new CryptoProvider();<br><br>const cookiesConfig = {<br>  httpOnly: true,<br>  path: &quot;/&quot;,<br>  secure: !dev,<br>};<br><br>export const redirectToAuthCodeUrl = async (event: RequestEvent) =&gt; {<br>  const { verifier, challenge } = await cryptoProvider.generatePkceCodes();<br>  const pkceCodes = {<br>    challengeMethod: &quot;S256&quot;,<br>    verifier,<br>    challenge,<br>  };<br>  const csrfToken = cryptoProvider.createNewGuid();<br>  const state = cryptoProvider.base64Encode(<br>    JSON.stringify({<br>      csrfToken,<br>      redirectTo: event.url.pathname,<br>    })<br>  );<br>  const authCodeUrlRequest = {<br>    redirectUri: REDIRECT_URI,<br>    responseMode: ResponseMode.QUERY,<br>    codeChallenge: pkceCodes.challenge,<br>    codeChallengeMethod: pkceCodes.challengeMethod,<br>    scopes: [],<br>    state,<br>  };<br><br>  try {<br>    const authCodeUrl = await msalInstance.getAuthCodeUrl(authCodeUrlRequest);<br>    event.cookies.set(&quot;pkceVerifier&quot;, verifier, cookiesConfig);<br>    event.cookies.set(&quot;csrfToken&quot;, csrfToken, cookiesConfig);<br>    return authCodeUrl;<br>  } catch (err) {<br>    console.log(err);<br>  }<br>};<br><br>export const getTokens = async (event: RequestEvent) =&gt; {<br>  const state = event.url.searchParams.get(&quot;state&quot;);<br>  if (state) {<br>    const decodedState = JSON.parse(cryptoProvider.base64Decode(state));<br>    const csrfToken = event.cookies.get(&quot;csrfToken&quot;);<br>    if (decodedState.csrfToken === csrfToken) {<br>      const code = event.url.searchParams.get(&quot;code&quot;);<br>      const error = event.url.searchParams.get(&quot;error&quot;);<br>      if (code) {<br>        const authCodeRequest = {<br>          redirectUri: REDIRECT_URI,<br>          code,<br>          scopes: [],<br>          codeVerifier: event.cookies.get(&quot;pkceVerifier&quot;),<br>        };<br>        try {<br>          const tokenResponse = await msalInstance.acquireTokenByCode(<br>            authCodeRequest<br>          );<br>          event.cookies.set(<br>            &quot;accessToken&quot;,<br>            tokenResponse.accessToken,<br>            cookiesConfig<br>          );<br>          event.cookies.set(&quot;idToken&quot;, tokenResponse.idToken, cookiesConfig);<br>          event.cookies.set(<br>            &quot;account&quot;,<br>            JSON.stringify(tokenResponse.account),<br>            cookiesConfig<br>          );<br>          return decodedState.redirectTo;<br>        } catch (err) {<br>          console.log(error);<br>        }<br>      } else if (error) {<br>        throw new Error(error);<br>      }<br>    } else {<br>      throw new Error(&quot;CSRF token mismatch&quot;);<br>    }<br>  } else {<br>    throw new Error(&quot;State parameter missing&quot;);<br>  }<br>};</pre><p>We have updated the <strong>redirectToAuthCodeUrl</strong> method to include a <strong>state</strong> object that has a GUID as a CSRF token and a “redirect to path”.</p><p>In the <strong>getTokens</strong> method we retrieve this state object from the query parameters to get the CSRF token and the “redirect to path”.</p><p>11. Finally we need to implement the <strong>logout</strong> functionality.</p><p>First, add a <strong>getLogoutUri </strong>method in the lib &gt; auth &gt; services.ts file as follows:</p><pre>export const getLogoutUri = () =&gt; {<br>  return `${msalConfig.auth.authority}/oauth2/v2.0/logout`;<br>};</pre><p>Next, under <strong>routes &gt; (protected)</strong> folder add a <em>+layout.ts</em> file and a “logout” folder with a <em>+server.ts</em> file. After this step, the folder structure should look like this:</p><figure><img alt="Folder structure after step 11" src="https://cdn-images-1.medium.com/max/259/1*ycHOLgTCmcXXdjXfhN_iIQ.png" /><figcaption>Folder structure after step 11</figcaption></figure><p>In the <strong>routes &gt; (protected) &gt; logout &gt; +server.ts</strong> file, add the following code:</p><pre>import { redirect } from &quot;@sveltejs/kit&quot;;<br>import type { RequestHandler } from &quot;./$types&quot;;<br>import { getLogoutUri } from &quot;$lib/auth/services&quot;;<br><br>export const GET: RequestHandler = async ({ cookies }) =&gt; {<br>  cookies.delete(&quot;accessToken&quot;);<br>  cookies.delete(&quot;idToken&quot;);<br>  cookies.delete(&quot;account&quot;);<br><br>  throw redirect(302, getLogoutUri());<br>};</pre><p>Finally update the <strong>routes &gt; (protected) &gt; +layout.ts</strong> with the following code:</p><pre>&lt;nav&gt;<br>    &lt;a href=&#39;/logout&#39;&gt;Logout&lt;/a&gt;<br>&lt;/nav&gt;<br><br>&lt;slot /&gt;<br><br>&lt;style&gt;<br>    :global(*) {<br>        margin: 0;<br>        padding: 0;<br>        box-sizing: border-box;<br>    }<br>    nav {<br>        display: flex;<br>        justify-content: end;<br>        padding: 20px;<br>        margin-bottom: 20px;<br>        box-shadow: 0 5px 5px 0 rgba(0, 0, 0, 0.25);<br>    }<br>    a {<br>        text-decoration: none;<br>        color: unset;<br>        border: 1px solid #000;<br>        border-radius: 2px;<br>        padding: 10px;<br>    }<br>    a:hover {<br>        background: rgba(0, 0, 0, 0.15);<br>    }<br>&lt;/style&gt;</pre><p>This should display a Logout button at the top of the page, clicking which should log the user out of the application.</p><p>The source code for the app can be found at <a href="https://github.com/varu87/sveltekit-aad-auth">https://github.com/varu87/sveltekit-aad-auth</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f596cfa8a349" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>