In .Net 8 Blazor web app template application how I can use azure active directory authentication

Kuldeep Y 36 Reputation points
2024-01-17T05:24:28.51+00:00

Hello, As we know when we create an application using Blazor Web App Template in .Net 8, we get project one for Server and another one for Client. so how azure authentication will apply/configure in this application.

More simply I just wanted know where I need to add Azure Authority,Client Id,Teanent Id etc. Then if this stuff in Server then what services or configuration i need to done in Program.cs of server and on other hand in Program.cs of Client and how i can implement Login and logout functionality in .NET 8 Blazor web app with using Auto render mode for per page interactivity ?

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,281 questions
Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,449 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,465 questions
Microsoft Entra ID
Microsoft Entra ID
A Microsoft Entra identity service that provides identity management and access control capabilities. Replaces Azure Active Directory.
20,068 questions
{count} votes

3 answers

Sort by: Most helpful
  1. Rumesh Manamendra 5 Reputation points
    2024-02-05T06:42:48.96+00:00

    It would be better if there was option to select Azure AD directly similar to MVC Project type

    1 person found this answer helpful.
    0 comments No comments

  2. Mahesh Deshmane 0 Reputation points
    2024-01-17T08:41:43.94+00:00

    Connecting to Azure Active Directory (Azure AD) in a .NET Blazor app follows the same steps, whether the project server and client blazor app. The process entails utilizing the Microsoft Authentication Library (MSAL) for .NET.

    1. Install Nuget Packages Microsoft.Identity.Client
    • Configure Authentication in Program.cs
       using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
       using Microsoft.Extensions.Configuration;
       using Microsoft.Extensions.DependencyInjection;
       using Microsoft.Identity.Client;
       
       public class Program
       {
           public static async Task Main(string[] args)
           {
               var builder = WebAssemblyHostBuilder.CreateDefault(args);
               
               builder.RootComponents.Add<App>("#app");
       
               builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
       
               // Add MSAL configuration
               builder.Services.AddMsalAuthentication(options =>
               {
                   builder.Configuration.Bind("AzureAd", options.ProviderOptions.Authentication);
               });
       
               await builder.Build().RunAsync();
           }
       }
       
       
    
    1. Add Azure AD Configuration in appsettings.json
       {
         "AzureAd": {
           "Authority": "https://login.microsoftonline.com/your-tenant-id",
           "ClientId": "your-client-id",
           "DefaultScopes": ["openid", "profile", "offline_access"]
         }
       }
       
       
    
    1. Use in the component
       <AuthorizeView>
        <Authorized>
            <p>Hello, @context.User.Identity.Name!</p>
        </Authorized>
        <NotAuthorized>
            <p>You are not logged in.</p>
        </NotAuthorized>
    </AuthorizeView>
       
    
    1. Access the user information
       @inject AuthenticationStateProvider AuthenticationStateProvider
       
       @code {
           private ClaimsPrincipal User;
       
           protected override async Task OnInitializedAsync()
           {
               var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
               User = authState.User;
           }
       }
       
       <p>Welcome, @User.Identity.Name!</p>
       
       
    

    This is a simplified example, and you may need to adjust it based on your specific requirements.

    • For login you can create a component
      @page "/login"
      
      <button @onclick="Login">Login</button>
      
      @code {
          private async Task Login()
          {
              await ((MsalAuthenticationStateProvider)AuthenticationStateProvider).SignIn();
          }
      }
      
      
    
    • For logout you can create a component
      @page "/logout"
      
      <button @onclick="Logout">Logout</button>
      
      @code {
          private async Task Logout()
          {
              await ((MsalAuthenticationStateProvider)AuthenticationStateProvider).SignOut();
          }
      }
      
      
    

    Include navigation links in your main layout or component to navigate to the login and logout pages. Ensure that you have implemented MsalAuthenticationStateProvider in your application. This provider is responsible for handling sign-in and sign-out actions.


  3. Jalpa Panchal-MSFT 480 Reputation points Microsoft Vendor
    2024-01-17T10:53:26.4066667+00:00

    Hi @Kuldeep Y, For the first question "where I need to add Azure Authority,Client Id,Teanent Id etc" => You could add this value in the server and clint side appsettings.json file as shown below:

    "AzureAd": {
            "Instance": "https://login.microsoftonline.com/",
            "Domain": "<Your-Domain>",
            "TenantId": "<Your-Tenant-Id>",
            "ClientId": "<Your-Client-Id>",
            "CallbackPath": "/signin-oidc"
         }
    

    Then if this stuff in Server then what services or configuration i need to done in Program.cs of server and on other hand in Program.cs of Client => Server side Program.cs:

    public void ConfigureServices(IServiceCollection services)
         {
             services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
                     .AddAzureADBearer(options => Configuration.Bind("AzureAd", options));
         }
         public void Configure(IApplicationBuilder app, IHostingEnvironment env)
         {
             app.UseAuthentication();
             // Other middleware
         }
    

    Client side Program.cs:

    var builder = WebAssemblyHostBuilder.CreateDefault(args);
        builder.Services.AddMsalAuthentication(options =>
        {
            builder.Configuration.Bind("AzureAd", options.ProviderOptions.Authentication);
            options.ProviderOptions.DefaultAccessTokenScopes.Add("api://<Your-Api-Client-Id>/access_as_user");
        });
        await builder.Build().RunAsync();
    

    login code:

    @page "/login"
        @inject NavigationManager Navigation
        @inject IAccessTokenProvider TokenProvider
        <h3>Login</h3>
        <button class="btn btn-primary" @onclick="LoginUser">Login with Azure AD</button>
        @code {
            private async Task LoginUser()
            {
                var result = await TokenProvider.RequestAccessToken();
                if (result.TryGetToken(out var token))
                {
                    Navigation.NavigateTo("/");
                }
                else
                {
                    Navigation.NavigateTo(result.RedirectUrl);
                }
            }
        }
    

    logout:

    @page "/logout"
        @inject NavigationManager Navigation
        @inject SignOutSessionStateManager SignOutManager
        <h3>Logout</h3>
        <button class="btn btn-primary" @onclick="LogoutUser">Logout from Azure AD</button>
        @code {
            private async Task LogoutUser()
            {
                await SignOutManager.SetSignOutState();
                Navigation.NavigateTo("authentication/logout");
            }
        }
    

    App.razor for Auto Render Mode:

    <Router AppAssembly="@typeof(Program).Assembly">
            <Found Context="routeData">
                <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
                    <NotAuthorized>
                        @if (!context.User.Identity.IsAuthenticated)
                        {
                            <RedirectToLogin />
                        }
                        else
                        {
                            <p>You do not have permission to view this page.</p>
                        }
                    </NotAuthorized>
                </AuthorizeRouteView>
            </Found>
            <NotFound>
                <LayoutView Layout="@typeof(MainLayout)">
                    <p>Sorry, there's nothing at this address.</p>
                </LayoutView>
            </NotFound>
        </Router>
        @code {
            private void RedirectToLogin()
            {
                var returnUrl = Uri.EscapeDataString(new Uri(Navigation.Uri).PathAndQuery);
                Navigation.NavigateTo($"login?returnUrl={returnUrl}");
            }
        }
    
    
    

    Best Regards, Jalpa

    ---If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments