Microsoft Entra ID Example

This is a quick guide on setting up Backoffice authentication with Microsoft Entra ID.

Prerequisites

In this example, you will need the following NuGet packages

Microsoft.Identity.Web
Microsoft.Identity.Web.TokenCache

Setting up Ucommerce Backoffice

Setting up Ucommerce backoffice with Microsoft Entra ID requires you to set up an external authentication scheme when calling .AddBackOffice()

To set up the authentication, use a helper method from the above packages to add all the required services to the AuthenticationBuilder. We highly recommend looking into some of these methods, as they do much of the groundwork to set up OpenID.

var ucommerceBuilder = builder.Services
    .AddUcommerce(builder.Configuration)
    .AddBackOffice(securitySettings =>
        {
            securitySettings.AddExternalIdentityProvider<MyExternalClaimsMapper>(
                OpenIdConnectDefaults.AuthenticationScheme,
                authenticationBuilder =>
                {
                    IEnumerable<string>? initialScopes = builder.Configuration["DownstreamApi:Scopes"]
                        ?.Split(' ');
                    // Use the AuthenticationBuilder from ASP.NET to set up authentication
                    authenticationBuilder.AddMicrosoftIdentityWebApp(builder.Configuration,
                            cookieScheme: null) // Ucommerce will handle the cookie session
                        .EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
                        .AddInMemoryTokenCaches();
                });
            // Configure Ucommerce to use your scheme from code
            securitySettings.UseExternalIdentityProvider(OpenIdConnectDefaults.AuthenticationScheme);
        }
    )
    ...

Remember to create your external claims mapper to map the claims from Azure to Ucommerce.

Create your Azure application

Follow this guide from Microsoft to set up your Azure App and appsettings.json. After following the guide, appsettings.json should look something like this

 ...
 "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "TenantId": "{Your-Tenant-Id}",
    "ClientId": "{Your-Client-Id}",
    "ClientCertificates": [
      {
        "SourceType": "StoreWithThumbprint",
        "CertificateStorePath": "CurrentUser/My",
        "CertificateThumbprint": "{Your-Certificate-Thumbprint}"
      }
    ],
    "CallbackPath": "/signin-oidc"
  },
  "DownstreamApi": {
    "BaseUrl": "https://graph.microsoft.com/v1.0/me",
    "Scopes": "user.read"
  },
...

Last updated