Summary: How to dynamically get Tenant ID for Microsoft users?
Details: I am writing a multi tenant app (C# and .NET Core) using which I want to create subscriptions and register for change notifications. I am using Microsoft Graph API v1.0 for this operation.
I followed this documentation to obtain the access token for a service account. After the app is registered and required permissions (e.g., User.Read, Mail.ReadWrite) are created, we need to grant admin consent for them
To do this programmatically,
Send a GET Request to:
https://login.microsoftonline.com/common/adminconsent?client_id={anyClientId}&state=12345&redirect_uri={redirectUrl}
This will take the user to an auth consent screen asking for the requested permissions.
Once granted, the user will redirected to "redirectUrl" from step 1 and tenantId and admin_consent will be present in the query params, e.g.,
https://example.com/auth?admin_consent=true&tenant={corresponding_tenant_id}
This tenantId can then be used to get an authenticated GraphClient for C# MVC applications. MSGraph SDK for .NET Reference
Question
Is there any other way to get this tenantId again for future use? I would prefer if the admin consent flow can be avoided each time that a request (other than sign-in) is made.
Example use case where tenant-id is needed again:
- Create GraphClient to fetch a particular message on receiving change notifications on a mailbox.
string tenantID = context.Ticket.Principal.FindFirst(AzureADConstants.TenantIdClaimType).Value;
Here is a multi tenant ASP.NET Core sample for your reference. azure.microsoft.com/en-gb/resources/samples/… – Tony Ju