.NET Core 3.1: from Identity to Azure Active Directory - how to do roles? Using Groups?

I've recently migrated my .NET Core 3.1 MVC application from Identity to AAD & couldn't believe how easy it was! Added below & removed references to Identity:

            var config = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", false)
            .Build();
      
            services.AddAuthentication(AzureADDefaults.AuthenticationScheme).AddAzureAD(options => config.Bind("AzureAd", options));
            services.AddControllers();

However - I used roles with Identity. Only 3 - used to decorate controllers & methods with an attribute to protect certain functionality. How do I set that up in AAD?

I saw AAD users can be assigned to AAD "Groups", but how do I get a user's group membership in a controller or Razor page once a user is logged in?


"how do I get a user's group membership in a controller or Razor page once a user is logged in"

You are trying to use AAD for Authentication but wanting to manually perform the Authorization on your code based on logged in user's group membership and assigning them to your App Roles. You can delegate this Authorization process to AAD itself. On your Azure App Registration, you can specify your App Roles and assign AAD Groups to each of those roles. When user successfully authenticates against AAD, based on their group membership, they are assigned the correct app roles on the claims token which are present in:

http://schemas.microsoft.com/ws/2008/06/identity/claims/role

You can read here about setting App Roles in Azure App Registration. Then the same Authorize attribute decoration [Authorize(Roles = "MyAppRoleName")] on your Controllers & Methods would continue to work.


@UserControl - indeed requires Premium.

Here's what I did on the cheap. App registrations / Token Configuration / Add option claim, and I added "groups". There's even a checkbox there to "Emit groups as role claims". Now they emit to the application under User.Claims.

In my app, I check claims where Type = 'roles', then assign to local roles via ClaimsIdentity.AddClaim(). Now controller Authorize attributes & Razor User.IsInRole() works as expected. Yay!