Get tenant Id

Anonymous
2023-07-25T06:14:37.9166667+00:00

Hello, is there an API to get the tenant ID of a specific domain in C#?

I want to send email using modern authentication and I need the tenant ID of each domain. I will be grateful if you provide a sample code.

Active Directory
Active Directory
A set of directory-based technologies included in Windows Server.
6,245 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,650 questions
0 comments No comments
{count} votes

Accepted answer
  1. navba-MSFT 20,890 Reputation points Microsoft Employee
    2023-07-26T09:34:40.5566667+00:00

    @Anonymous Apologies for the late reply. Welcome to Microsoft Q&A Forum, Thank you for posting your query here!

    I understand that you need an API to get the tenant ID of a specific domain in C#.

    You can perform the GET Request on the below REST API endpoint. You need to replace the MyCompanyContoso with your concerned domain.

    https://login.windows.net/MyCompanyContoso.onmicrosoft.com/.well-known/openid-configuration.

    The returned JSON response has the tenant ID (72f988bf-XXX-XXXX-XXXX-2d7cd011db47) in it. See the sample response below:

    {
       "authorization_endpoint" : "https://login.windows.net/72f988bf-XXX-XXXX-XXXX-2d7cd011db47/oauth2/authorize",
       "check_session_iframe" : "https://login.windows.net/72f988bf-XXX-XXXX-XXXX-2d7cd011db47/oauth2/checksession",
       "end_session_endpoint" : "https://login.windows.net/72f988bf-XXX-XXXX-XXXX-2d7cd011db47/oauth2/logout",
       "id_token_signing_alg_values_supported" : [ "RS256" ],
       "issuer" : "https://sts.windows.net/72f988bf-XXX-XXXX-XXXX-2d7cd011db47/",
       "jwks_uri" : "https://login.windows.net/common/discovery/keys",
       "microsoft_multi_refresh_token" : true,
       "response_modes_supported" : [ "query", "fragment", "form_post" ],
       "response_types_supported" : [ "code", "id_token", "code id_token", "token" ],
       "scopes_supported" : [ "openid" ],
       "subject_types_supported" : [ "pairwise" ],
       "token_endpoint" : "https://login.windows.net/72f988bf-XXX-XXXX-XXXX-2d7cd011db47/oauth2/token",
       "token_endpoint_auth_methods_supported" : [ "client_secret_post", "private_key_jwt" ],
       "userinfo_endpoint" : "https://login.windows.net/72f988bf-XXX-XXXX-XXXX-2d7cd011db47/openid/userinfo"
    }
    

    The above is legacy endpoint though. However it still does work. You don't need to pass the auth token for this to work.

    Alternatively, You can also call the List Tenants REST API , to get the tenants for your account. This requires your bearer token to be passed though.

    Here is a sample code which you need to tweak accordingly.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net.Http.Headers;
    using System.Net.Http;
    using System.Text;
    using System.Threading.Tasks;
    using System.Xml.Linq;
    using Microsoft.Graph;
    using Microsoft.Identity.Client;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Threading.Tasks;
    using Newtonsoft.Json.Linq;
    using System.Text.Json;
    
    namespace cSharpTenantIdFinder
    {
        internal class Program
        {
            static async Task Main(string[] args)
            {
           
                var accessToken = "eyJ0eXAiOXXXXXXXXXXXXXXXXX";
    
                using (var httpClient = new HttpClient())
                {
                    // Set the base address for the API
                    httpClient.BaseAddress = new Uri("https://management.azure.com/");
    
                    // Set the Authorization header with the access token
                    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
    
    
                    try
                    {
                        // Make the API request
                        HttpResponseMessage response = await httpClient.GetAsync("tenants?api-version=2020-01-01");
    
                        // Check if the request was successful
                        if (response.IsSuccessStatusCode)
                        {
                            // Read the response content as a string
                            string responseBody = await response.Content.ReadAsStringAsync();
    
                            // Process the response as needed (e.g., parse the JSON response)
                            // Console.WriteLine(responseBody);
    
                            // Deserialize the JSON response
                            var jsonOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
                            var responseObj = JsonSerializer.Deserialize<TenantResponseWrapper>(responseBody, jsonOptions);
    
                            // Process the tenants data and display the required properties
                            foreach (var tenant in responseObj.Value)
                            {
                                Console.WriteLine($"Tenant ID: {tenant.TenantId}");
                                Console.WriteLine($"Default Domain: {tenant.DefaultDomain}");
                                Console.WriteLine($"Tenant Type: {tenant.TenantType}");
                                Console.WriteLine($"Domains:");
                                foreach (var domain in tenant.Domains)
                                {
                                    Console.WriteLine($"  {domain}");
                                }
                                Console.WriteLine();
                                Console.ReadLine();
                            }
                        }
                        else
                        {
                            // Handle the error if the request was not successful
                            Console.WriteLine($"Request failed with status code {response.StatusCode}: {response.ReasonPhrase}");
                        }
                    }
                    catch (Exception ex)
                    {
                        // Handle any exceptions that occurred during the request
                        Console.WriteLine($"Error occurred during the request: {ex.Message}");
                    }
                }
            }
        }
        // Define classes to represent the JSON response
        public class Tenant
        {
            public string TenantId { get; set; }
            public string DefaultDomain { get; set; }
            public string TenantType { get; set; }
            public string[] Domains { get; set; }
        }
    
        public class TenantResponseWrapper
        {
            public Tenant[] Value { get; set; }
        }
    }
    
    

    **

    Hope this helps. If you have any follow-up questions, please let me know. I would be happy to help.

    Please do not forget to "Accept the answer” and “up-vote” wherever the information provided helps you, this can be beneficial to other community members.

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful