Ryan Richardson
Ryan Richardson

Reputation: 1

How to setup authorization for ASP.NET Core Web App with Azure AD and AppRoles?

How can I setup authorization for my Azure ASP.NET Core Web App MVC .NET 6 with Azure Active Directory using AppRoles? If that is not the recommended approach, I welcome suggested approaches.

I have been following the msft learn documentation [https://learn.microsoft.com/en-us/azure/app-service/overview-authentication-authorization?toc=%2Faspnet%2Fcore%2Ftoc.json&bc=%2Faspnet%2Fcore%2Fbreadcrumb%2Ftoc.json&view=aspnetcore-6.0](azure app service authorization) as well as [https://learn.microsoft.com/en-us/azure/active-directory/develop/howto-add-app-roles-in-azure-ad-apps](azure ad how to add app roles), but haven't been able to get that to work when I deploy to the app service. The authentication with Azure AD is working, and authorization works locally in Visual Studio, but not when deployed to the app service. I receive access denied when navigating to a view with [Authorize(Role = "ContainerRestart")] when my user is assigned that role.

Here is most of the code in the program.cs file.

builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(options =>
    {
        options.GetClaimsFromUserInfoEndpoint = true;
        builder.Configuration.Bind("AzureAd", options);
        options.Events.OnTokenValidated = async context =>
        {
            await Task.FromResult(0);
        };
        options.SaveTokens = true;
        options.TokenValidationParameters.RoleClaimType = ClaimTypes.Role;
    })
    .EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
    .AddMicrosoftGraph(builder.Configuration.GetSection("MicrosoftGraph"))
    .AddInMemoryTokenCaches();

builder.Services.AddAuthorization(options =>
{
    options.FallbackPolicy = options.DefaultPolicy;
});

builder.Services.AddControllersWithViews(options =>
{
    var policy = new AuthorizationPolicyBuilder(OpenIdConnectDefaults.AuthenticationScheme)
        .RequireAuthenticatedUser()
        .Build();
    options.Filters.Add(new AuthorizeFilter(policy));
});
builder.Services.AddHttpClient();

builder.Services.AddRazorPages()
    .AddMicrosoftIdentityUI();

var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();

In Azure AD I have created the AppRole "ContainerRestart" and assigned my user to that role. In the controller I have added [Authorize(Role = "ContainerRestart")].

Since the code works locally in Visual Studio, it leads me to beleive that there maybe a misconfiguration of the web app, but I am unable to figure out what I am missing. Please help, thank you!

Upvotes: 0

Views: 688

Answers (0)

Related Questions