authenticationblazor-server-sidemicrosoft-entra-id

How to implement user authentication in Blazor Server with Entra External ID?


I am developing a Blazor Server application (.net 9) with Cosmos DB as database. I would like to add user auth with Entra External ID.

The only good docs I found are with Asp.Net MVC, here:

https://learn.microsoft.com/en-us/entra/external-id/customers/tutorial-web-app-dotnet-sign-in-prepare-app

Does anyone have a github example app with Blazor? Or a link to tutorial?


Solution

  • I managed to make it work with the following steps.

    Entra External ID Steps

    1. Create an external tenant: https://learn.microsoft.com/en-us/entra/external-id/customers/how-to-create-external-tenant-portal

    2. Prepare your external tenant: https://learn.microsoft.com/en-us/entra/external-id/customers/tutorial-web-app-dotnet-sign-in-prepare-tenant

    Blazor Application Steps

    1. Add package Microsoft.Identity.Web: https://www.nuget.org/packages/Microsoft.Identity.Web

    2. Configure your Blazor application in appsettings.json: https://learn.microsoft.com/en-us/entra/external-id/customers/tutorial-web-app-dotnet-sign-in-prepare-app#configure-the-application-for-authentication

    3. Add authentication and authorization to program.cs

    builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
        .AddMicrosoftIdentityWebApp(builder.Configuration)
        .EnableTokenAcquisitionToCallDownstreamApi()
        .AddInMemoryTokenCaches();
    
    builder.Services.AddCascadingAuthenticationState();
    ...
    
    app.UseAuthentication();
    app.UseAuthorization();
    
    1. Add authorization at the page level. Before the page is rendered, it will ask for the user be authenticated: https://learn.microsoft.com/en-us/aspnet/core/blazor/security/?view=aspnetcore-9.0&tabs=visual-studio#authorize-attribute

    2. Add authorization at the component level. The page is rendered, but some components are only displayed to authenticated users: https://learn.microsoft.com/en-us/aspnet/core/blazor/security/?view=aspnetcore-9.0&tabs=visual-studio#authorizeview-component

    3. Add authorization at the code level: https://learn.microsoft.com/en-us/aspnet/core/blazor/security/?view=aspnetcore-9.0&tabs=visual-studio#procedural-logic