In my ASP.NET MVC Core project, I want all the AppRoles that are set up in the App Registration as a list to display in my view.
Currently I have attempted the following:
var servicePrincipal = await _graphServiceClient.Applications[_configuration["AzureAd:AppRegistrationId"]]
.Request()
.Select("appRoles")
.GetAsync();
I have granted the application the API permissions Application.Read.All
and Directory.Read.All
, but I still get error:
ServiceException: Code: Authorization_RequestDenied
Message: Insufficient privileges to complete the operation
Questions:
Thank you in advance for any assistance!
looks like I'm late...
I test with delegated permission and application permission, both of them are ok.
for application permission, it would be easy to do it with code like below:
using Microsoft.Graph;
using Azure.Identity;
var scopes = new[] { "https://graph.microsoft.com/.default" };
var tenantId = "tenantId ";
var clientId = "clientId ";
var clientSecret = "clientSecret ";
var clientSecretCredential = new ClientSecretCredential(
tenantId, clientId, clientSecret);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
var res = await graphClient.Applications["azure_ad_app_object_id_instead_of_client_id"].Request().GetAsync();
var roles = res.AppRoles;
This requires application type of api permission:
If we want to use the delegated api permission, since this is an MVC application, we need to integrate AAD authentication into the application first. We can follow this sample. To generally speaking, add codes in program.cs like this:
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme) .AddMicrosoftIdentityWebApp(builder.Configuration) .EnableTokenAcquisitionToCallDownstreamApi() .AddMicrosoftGraph(builder.Configuration.GetSection("DownstreamApi")) .AddInMemoryTokenCaches();
builder.Services.AddControllersWithViews(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
}).AddMicrosoftIdentityUI();
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "TenantId",
"TenantId": "TenantId",
"ClientId": "ClientId",
"ClientSecret": "ClientSecret",
"CallbackPath": "/home", //don't forget to set redirect url in azure portal
"SignedOutCallbackPath ": "/signout-callback-oidc"
},
Then inject graphclient
into the code and use it call graph api,
private readonly GraphServiceClient _graphServiceClient;
public HomeController(GraphServiceClient graphServiceClient)
{
_graphServiceClient = graphServiceClient;
}
public async Task<IActionResult> IndexAsync() {
var b = await _graphServiceClient.Applications["aad_app_object_id"].Request().GetAsync();
return View();
}