1
votes

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,

  1. Send a GET Request to: https://login.microsoftonline.com/common/adminconsent?client_id={anyClientId}&state=12345&redirect_uri={redirectUrl}

  2. This will take the user to an auth consent screen asking for the requested permissions.

  3. 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.
1
You can also use Active Directory Authentication Library (ADAL). After you login, you can get the tenantId like this. 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
And you can get access token by using AcquireTokenSilentAsync methodTony Ju
@CaiyiJu I did go through the link that you had posted in an earlier comment, and it feels like an overkill for what I want to acheive. Can't I store this tenant-id locally for future use? Are there any pitfalls of doing this ?Swasti Gupta

1 Answers

0
votes
  1. In most cases, you can use tenant name to replace the tenant ID. And, you can get the tenant name from the email address.

  2. Based on your description, your application will manage the user's mailbox on behalf of the user. In this scenario, your application will have an access token for the user. Then you can get the tenant ID by making a GET request to https://management.azure.com/tenants?api-version=2016-06-01 with the token.