Grant an existing B2C app access to graph API - azure-ad-b2c

I have an existing B2C app that I want to give graph access to.
I set this up previously but now want to replicate it but everything i can find is for new apps. I ysed the older graph but i think the article I used has been moved as everything is talking about the new Graph api
Is there a specific article for this, also if anyone has seen an article that describes the process from moving from Azure graph to Microsoft Graph (the new version) for a B2C app that would be great
Thanks

Register the application for the Graph API
In addition to registering the application in the B2C directory,
we must also create an application registration for the graph API.
The three key/id values you will need are the tenantId, ObjectId,
and AppPrincipalId.
To get the tenantId, log into the azure ad b2c directory in the new portal.
https://portal.azure.com/
Be sure you have the correct directory selected after you login
(top right corner).
Click on the help button (a question mark inside a circle) near the
top right corner of the page. In the menu that appears, click the
"Show diagnostics" option. This will display a JSON formatted output in
a new popup/window. Look for the "tenants" array and find the entry
with the display name of the directory you wish to register with the
application. The "id" attribute of that entry is the tenantId.
Example:
{
"clientSessionStartDate": {
//stuff will be here ...
},
//
// more shtuff you don't care about will be here ...
//
"tenants": [
{
"id": "SomeUUIDwithlike36charactersSometime",
"domainName": "yourtenantname.onmicrosoft.com",
"displayName": "displanynameoftenant",
"isSignedInTenant": true
},
// ... snippity lemon
]
// ... snip some more
}
You will also need a unique application Secret and AppPrincipalId to be
generated for the new application.
Also, to set the correct permissions for the application, you will need
its "ObjectId".
The process for registering the application and generating those values
is more complicated, and requires a special module for PowerShell
and the online login module to be downloaded and installed.
Also, be sure you have the latest version of PowerShell installed for
your system, or you will not be able to use the azure module.
Sign-In assistant: https://www.microsoft.com/en-us/download/details.aspx?id=41950
Azure AD PowerShell Module: http://go.microsoft.com/fwlink/p/?linkid=236297
Create the application registration with PowerShell
This next section is an almost verbatim copy-paste fo the documentation.
https://azure.microsoft.com/en-us/documentation/articles/active-directory-b2c-devquickstarts-graph-dotnet/
After you install the PowerShell module, open PowerShell and connect to
your B2C tenant.
> $msolcred = Get-Credential
After you run Get-Credential, you will be prompted for
a user name and password, Enter the user name and password
of your B2C tenant administrator account.
> Connect-MsolService -credential $msolcred
Before you create your application, you need to generate a new client
secret. Your application will use the client secret to authenticate to
Azure AD and to acquire access tokens. You can generate a valid secret
in PowerShell:
> $bytes = New-Object Byte[] 32
> $rand = [System.Security.Cryptography.RandomNumberGenerator]::Create()
> $rand.GetBytes($bytes)
> $rand.Dispose()
> $newClientSecret = [System.Convert]::ToBase64String($bytes)
> $newClientSecret
The final command should print your new client secret. Copy it somewhere safe. You'll need it later. Now you can create your application by providing the new client secret as a credential for the app:
> New-MsolServicePrincipal -DisplayName "My New B2C Graph API App" -Type password -Value $newClientSecret
Example output:
DisplayName : My New B2C Graph API App
ServicePrincipalNames : {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}
ObjectId : xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
AppPrincipalId : xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
TrustedForDelegation : False
AccountEnabled : True
Addresses : {}
KeyType : Password
KeyId : xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
StartDate : 1/1/2017 1:33:09 AM
EndDate : 1/1/2017 1:33:09 AM
Usage : Verify
If you successfully create the application, it should print out
properties of the application like the ones above, but with a mix of alpha-numeric characters. You'll need both
ObjectId and AppPrincipalId, so copy those values, too.
You will also need the tenant ID of the B2C directory.
After you create an application in your B2C tenant, you need to assign
it the permissions it needs to perform user CRUD operations. Assign the
application three roles: directory readers (to read users), directory
writers (to create and update users), and a user account administrator
(to delete users). These roles have well-known identifiers, so you can
replace the -RoleMemberObjectId parameter with ObjectId from above and
run the following commands. To see the list of all directory roles,
try running Get-MsolRole.
> Add-MsolRoleMember -RoleObjectId 88d8e3e3-8f55-4a1e-953a-9b9898b8876b -RoleMemberObjectId <Your-ObjectId> -RoleMemberType servicePrincipal
> Add-MsolRoleMember -RoleObjectId 9360feb5-f418-4baa-8175-e2a00bac4301 -RoleMemberObjectId <Your-ObjectId> -RoleMemberType servicePrincipal
> Add-MsolRoleMember -RoleObjectId fe930be7-5e62-47db-91af-98c3a49a38b1 -RoleMemberObjectId <Your-ObjectId> -RoleMemberType servicePrincipal
You now have an application that has permission to create, read,
update, and delete users from your B2C tenant.

I totally forgot this great answer exists and this is how you do it
Authorize By Group in Azure Active Directory B2C

Related

How can I grant consent to my own app in azure, in case I am not global admin in tenant?

Given I have created an app using this repository in Azure.
And this app is deployed using a Service Principal which was created by below command:
az ad sp create-for-rbac --name "fxpricepredictor" --role contributor --scopes "/subscriptions/YOUR-SUBSCRIPTION-ID/resourceGroups/YOUR-RESOURCE-GROUP-NAME" --sdk-auth
Now, I need to get the API token to manage my created resources using REST APIs.
Based on documentation, I should be able use my tenantId, clientId and client_secret to get the token by calling the bellow endpoint:
curl: POST
https://login.microsoftonline.com/{{tenantId}}/oauth2/token
Please notice that, I am not the global admin in the tenant.
The official sample postman collection is here and here is how my request looks like in postman:
Sadly the endpoint does not provide me the token and instead it returns such error:
{
"error": "unauthorized_client",
"error_description": "AADSTS700016: Application with identifier 'MY_CLIENTID' was not found in the directory 'MY COMPANY'. This can happen if the application has not been installed by the administrator of the tenant or consented to by any user in the tenant. You may have sent your authentication request to the wrong tenant.\r\nTrace ID: 5a9a2c53-c3c8-46da-a1a6-551b42082400\r\nCorrelation ID: bf7c5966-ffa4-4312-8a77-434c2560d65a\r\nTimestamp: 2022-10-05 14:54:23Z",
"error_codes": [
700016
],
"timestamp": "2022-10-05 14:54:23Z",
"trace_id": "5a9a2c53-c3c8-46da-a1a6-551b42082400",
"correlation_id": "bf7c5966-ffa4-4312-8a77-434c2560d65a",
"error_uri": "https://login.microsoftonline.com/error?code=700016"
}
please notice, I hided some sensitive values in error response by MY_CLIENTID and MY COMPANY
So, i guess, the main reason that i am facing this issue is that:
This can happen if the application has not been consented to by any user in the tenant.
Meaning that, i should consent my own app. Am I right ?
So, my question is:
How can i get the token to work with REST APIs to manage my resources ?
How can I grant consent to my own app, given that I am not a global Admin ?
Update:
As I figured out, I should be able to Grant Consent to my app using "Microsoft Graph permissions reference". And here is what i have done:
Login to Azure portal
Navigate to "Azure Active Directory"
Navigate to "App registrations"
Click on the created APP ("fxpricepredictor")
Navigate to "API permissions"
Click "Add a permission"
Click on "Microsoft Graph"
Choose "Delegated Permissions"
Search for "authentication" ---> (Sadly this option also requiereds Admin Consent)
I tried to reproduce the same in my environment and got the below results:
When I ran the same command as you, one Azure AD application named fxpricepredictor is automatically created with details like below:
az ad sp create-for-rbac --name "fxpricepredictor" --role contributor --scopes "/subscriptions/<subscriptionID>/resourceGroups/<resourcegroupName>" --sdk-auth
By including above details as parameters, I am able to generate access token successfully via Postman like below:
Please note that, I don't have global administrator role and granting admin_consent is not really required.
With the above access token, I am able to fetch and manage the Azure resources in that resource group like below:
GET https://management.azure.com/subscriptions/<subscriptionID>/resourceGroups/SriTest/resources?api-version=2021-04-01
Response:
The error AADSTS700016 may also occur if there is no application in your tenant with provided ClientID.
I tried including random ClientID which does not exist in Azure AD tenant and got same error as below:
So, make sure to check whether the application is existing or not with the given ClientID in Azure AD tenant.

Azure Keyvault - "The operation "List" is not enabled in this key vault's access policy." while creating keyvault programmatically

I am creating azure keyvault using .net core 2.1 with OpenIdConnect with following AccessPolicies
AccessPolicies = new List<AccessPolicyEntry>()
{
new AccessPolicyEntry
{
TenantId = Guid.Parse(tenantId),
ObjectId = objectId,
Permissions = new Permissions
{
Secrets = new List<string> { "all" },
Keys = new string[] { "all" },
Certificates = new string[]{"all" }
}
}
}
using that, now, I can create keyvault but while go to newly created keyvault(in Azure portal) settings blade {Key,Secrete,Certificate} it shows warning
"The operation "List" is not enabled in this key vault's access policy."
Note :- As shown in above code "All permission are given".I can see it in azure portal.
What I have tried :-
I have tried to refer following stack-overflow already question-answer
Azure Keyvault - "Operation "list" is not allowed by vault policy" but all permissions are checked
How do I fix an "Operation 'set' not allowed" error when creating an Azure KeyVault secret programmatically?
according to above stackoverflow answer(s) "need to pass the object ID of the service principal of the Azure AD application instead of object ID of your Azure AD application".
I have tried to find out object ID of the service principal of the azure AD application using following powershell script
Get-AzADServicePrincipal -ServicePrincipalName "<app client ID>"
it gives following result
I have tried to use "Id"(in above screenshot) in objectId of AccessPolicyEntry but it not solved problem.
Question :-
Is any other permission need to set in AccessPolicyEntry?
What should be the objectID in AccessPolicyEntry(currently, I am giving obectId of Azure AD application)?
If needed objectId of service princpal. how can get it programmatically?
Well, I can reproduce your issue on my side.
First, the operation pass the object ID of the service principal instead of object ID of your Azure AD application is completely correct. After giving all the permissions to the service principal in the Access policies, the service principal will have the permissions.
But when you check the keyvault in the portal, you are using your user account which login the azure portal instead of the service principal, it caused the warning.
So if you want to fix the warning, just add your user account in the Access policies via + Add Access Policy button in the portal, or you can specify the object id of your user account in your code with the permissions when creating the keyvault.
Then about your questions:
Is any other permission need to set in AccessPolicyEntry?
No, the permissions are enough.
What should be the objectID in AccessPolicyEntry(currently, I am giving obectId of Azure AD application)?
You should not use the object id of the AD App, your option is to use the object id of the service principal/security group/user account, it depends on your requirement, details here.
If needed objectId of service principal. how can get it programmatically?
You can use the powershell command as you used, or the Azure CLI az ad sp show via the service principal name.
Or if you could use Microsoft Graph SDK for C# along with the filter, something like:
GraphServiceClient graphClient = new GraphServiceClient( authProvider );
var serviceprincipals = await graphClient.Serviceprincipals
.Request().
.Filter("some condition").
.GetAsync();

Grant O365 Mailbox Permission to a Managed Identity

Trying to get an Logic App to get email message details via Graph API because the O365 Outlook Connector does not provide the output I need but Graph API does (Internet message headers).
The Outlook connector creates an API Connection for authentication and that works great.
To call Graph API I am using the HTTP action and it supports Managed Identity, so I'm wondering:
Can I grant permission such that the Managed Identity can read a certain mailbox?
Can the HTTP action use an API Connection (similar to what the Outlook connector does)?
1.Can I grant permission such that the Managed Identity can read a certain mailbox?
The managed identity is a service principal, which we can check it and its permissions in the Azure portal -> Azure Active Directory -> Enterprise applications. But we could not add new permissions in that, so we need to create a new AD App in the App registrations, add credentials to your app
, then grant the Mail.Read application permission of Microsoft Graph API, refer to this link. The permission is to call this api List messages(I suppose you want to use this api, if not, just follow the doc to find the application permission, add it.) At last, don't forget to click the Grant admin consent button.
In the logic app, use Active Directory OAuth for Authentication, https://graph.microsoft.com/ for Audience, and specific the URL, Client id, secret, etc, what need to call the MS graph api. xxx#microsoft.com is the user principal name, also is the mailbox address. I am not sure I understand the read a certain mailbox in your question correctly enough, if you mean you want to grant the permission just for only one mailbox, I will say there is no such permission in Microsft graph.
2.Can the HTTP action use an API Connection (similar to what the Outlook connector does)?
There is no pre-bulit connector for http action, you could try the Custom connectors in Logic Apps.
There is a way to add that application role permission to the Managed Identity. It is not possible to do that using the Azure Portal. You can verify in the Azure Portal that the steps below worked though. This method saves you creating a principal yourself and removes the need for client id/secret bookkeeping.
When you use Powershell, it is possible to add the Mail.Read application role permission to a managed identity, be it a system managed or user managed identity. There are other ways of performing the same steps, e.g. Azure CLI. But below is what I know works and have used.
The steps are usable for any identity and application with assignable app roles. So you can also add Sharepoint permissions to list sites, open an Excel sheet. But keep in mind that the Microsoft app roles are mostly all or nothing. It breaks the principle of least priviliged permissions.
I would love to know a generic way to avoid breaking the principle.
To assign an app role permission to a managed identity we need to know a couple of things:
the id of...
...the managed identity (e.g. "logic-app-identity")
...the application that has the application role (e.g. "Microsoft Graph")
...the id of the application role to assign to the managed identity (e.g. "Mail.Read")
And then we can assign the app role to the managed identity.
Set up some variables for readability
$managed_identity_name = "logic-app-identity"
$application_with_the_required_role_name = "Microsoft Graph"
$application_role_to_assign_name = "Mail.Read"
Use AzureAD module and login.
Use the AzureAd module from here
Import-Module AzureAd
Connect-AzureAd #shows popup to login
1. Get the managed identity id
# filter first server side, and in case of multiple results, the where ensures a single result
# -All is necessary because a managed identity is a sort of service principal
$managed_identity_id = (Get-AzureADServicePrincipal -All $true -SearchString $managed_identity_name | where DisplayName -eq $managed_identity_name).ObjectId
2. Get the application with the requested application roles
# -SearchString on "Microsoft Graph" returns two results, therefore the where clause to ensure a single result
# storing the returned object, because it contains the approles array
$application_with_the_required_role = (Get-AzureADServicePrincipal -SearchString "Microsoft Graph" | where DisplayName -eq "Microsoft Graph")
# fun fact: the ObjectId of the "Microsoft Graph" application is always: 94d0e336-e38a-4bfc-9b21-8fbb74b6b835
$application_with_the_required_role_id = $application_with_the_required_role.ObjectId
3. Get the application role id to assign to the managed identity
# the required id is now simply called Id
# fun fact: the ObjectId of the "Mail.Read" app role is always: 810c84a8-4a9e-49e6-bf7d-12d183f40d01
$application_role_to_assign_id = ($application_with_the_required_role.AppRoles | where Value -eq $application_role_to_assign_name).Id
Assign the app role to the managed identity
New-AzureADServiceAppRoleAssignment -ObjectId $managed_identity_id -PrincipalId $managed_identity_id -ResourceId $application_with_the_required_role_id -Id $application_role_to_assign_id
BONUS: verify-ish the assignment
# should list the assigned application to the identity, dig further for the specific app role
# (I don't know how :S)
Get-AzureADServiceAppRoleAssignedTo -ObjectId $managed_identity_id | fl
# and the other way around to list the identities assigned to the application
Get-AzureADServiceAppRoleAssignment -ObjectId $application_with_the_required_role_id | fl

Add AAD application as a member of a security group

I'm trying to enable service to service auth using AAD tokens. My plan is to validate "groups" claim in the token to make sure the caller is a member of a security group that we created.
For example, we will create group1 for readers and group2 for writers. Then based on "groups" claim, I will figure out the right access level.
I use AAD app to issue the tokens (not a user), so I need that app to be a member of the security group. Azure AD powershell doesn't seem to accept application ids as group members. How to solve this? are there any other recommended patterns when the caller is another AAD app?
Command used:
https://learn.microsoft.com/en-us/powershell/module/azuread/Add-AzureADGroupMember?view=azureadps-2.0
Error:
Add-AzureADGroupMember : Error occurred while executing AddGroupMember
Code: Request_BadRequest
Message: An invalid operation was included in the following modified references: 'members'.
RequestId: 0441a156-3a34-484b-83d7-a7863d14654e
DateTimeStamp: Mon, 11 Dec 2017 21:50:41 GMT
HttpStatusCode: BadRequest
HttpStatusDescription: Bad Request
HttpResponseStatus: Completed
At line:1 char:1
+ Add-AzureADGroupMember -ObjectId "9c2cdf89-b8d6-4fb9-9116-7749adec85c ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Add-AzureADGroupMember], ApiException
+ FullyQualifiedErrorId : Microsoft.Open.AzureAD16.Client.ApiException,Microsoft.Open.AzureAD16.PowerShell.AddGroupMember
Unfortunately, you cannot add an application as a member of Azure AD group.
Though the official document for the Powershell cmdlet Add-AzureADGroupMember doesn't make clear you cannot use Application's ObjectId as the RefObjectId, absolutely you cannot use it.
You cannot add an application as a member of Azure AD group neither.
For example, we will create group1 for readers and group2 for writers.
Then based on "groups" claim, I will figure out the right access
level.
For your scenario, I'm afraid that you couldn't achieve this for now. I understand why you need this. According to your request, my thought is assigning your application from Enterprise Application to Groups or users and manger users with different access rights. However, you cannot choose more roles for the selected group. The only one role is default access If want to define more roles for the app, you can refer to this documentation.
I also tried to use Azure AD RBAC and create new conditional access for my test app,but all don't have read only this choice.
You can also put your idea in Azure Feedback Forum, azure team will see it. Also, I will upvote your idea.
Update:
Currently, you can add a service principal to an AAD Group:
Example:
$spn = Get-AzureADServicePrincipal -SearchString "yourSpName"
$group = Get-AzureADGroup -SearchString "yourGroupName"
Add-AzureADGroupMember -ObjectId $($group.ObjectId) -RefObjectId $($spn.ObjectId)
Updated 2:
Recently, I also see lots of users want to assign roles to a service principal to let the service principal have some permissions to access to the app with a role.
I want to make clear here. Role-based authorized should be used for users, NOT applications. And it's not designed for applications. If you want to give some different permissions you may consider to assign application permissions to your service principal instead.
You can expose your Web App/API with application permissions by editing the Manifest in app registrations.
You can go to Azure portal > Azure Active Directory > App registrations > Select your App > Manifest.
In appRoles, you can insert content like this:
{
"allowedMemberTypes": [
"Application"
],
"displayName": "Access to the settings data",
"id": "c20e145e-5459-4a6c-a074-b942bbd4cfe1",
"isEnabled": true,
"description": "Administrators can access to the settings data in their tenant",
"value": "Settingsdata.ReadWrite.All"
},
Then, you can go another app registration you want to give permission > Settings > require permissions > Add > Search the application name you want to access > Choose the application permission you created before.
Therefore, your sp can obtain a token with that application permissions in token claims.
Also, for authorization from the resource, you need to add code logic to give control policy for that token with Settingsdata.ReadWrite.All claim.
Update 3
Currently, you can add the service principal to one AAD Group directly in Azure portal:
Following Update 3 in the answer of #Wayne Yang, I've successfully implemented this using C# and the MS Graph SDK.
But I think the same should be possible using Powershell and simple REST API calls.
// create new application registration
var app = new Application
{
DisplayName = principal.DisplayName,
Description = principal.Description,
};
app = await _graphClient.Applications.Request().AddAsync(app);
// create new service Principal based on newly created application
var servicePrincipal = new ServicePrincipal
{
AppId = app.AppId
};
// add service principal
servicePrincipal = await _graphClient.ServicePrincipals.Request().AddAsync(servicePrincipal);
// add service principal to existing security group
await _graphClient.Groups[groupId].Members.References.Request().AddAsync(servicePrincipal);

How to get the azure account tenant Id?

My question is: Is it possible to get the azure active directory tenant id without using powershell command?
I found this two blogs and with this help, I'm already able to get the tenant ID and subscriptions ID from powershell. Is it the only way to retrieve the tenant?
Get Windows Azure Active Directory Tenant ID in Windows PowerShell
Windows Azure AD authentication support for PowerShell
Thanks
Time changes everything. I was looking to do the same recently and came up with this:
Note
added 02/17/2021
Stable Portal Page thanks Palec
added 12/18/2017
As indicated by shadowbq, the DirectoryId and TenantId both equate to the GUID representing the ActiveDirectory Tenant. Depending on context, either term may be used by Microsoft documentation and products, which can be confusing.
Assumptions
You have access to the Azure Portal
Solution
The tenant ID is tied to ActiveDirectoy in Azure
Navigate to Dashboard
Navigate to ActiveDirectory
Navigate to Manage / Properties
Copy the "Directory ID"
Azure ActiveDirectory Tenant ID:
Go to https://login.windows.net/YOURDIRECTORYNAME.onmicrosoft.com/.well-known/openid-configuration and you'll see a bunch of URLs containing your tenant ID.
My team really got sick of trying to find the tenant ID for our O365 and Azure projects. The devs, the support team, the sales team, everyone needs it at some point and never remembers how to do it.
So we've built this small site in the same vein as whatismyip.com. Hope you find it useful!
How to find my Microsoft 365, Azure or SharePoint Online tenant ID?
In the Azure CLI (I use GNU/Linux):
$ azure login # add "-e AzureChinaCloud" if you're using Azure China
This will ask you to login via https://aka.ms/devicelogin or https://aka.ms/deviceloginchina
$ azure account show
info: Executing command account show
data: Name : BizSpark Plus
data: ID : aZZZZZZZ-YYYY-HHHH-GGGG-abcdef569123
data: State : Enabled
data: Tenant ID : 0XXXXXXX-YYYY-HHHH-GGGG-123456789123
data: Is Default : true
data: Environment : AzureCloud
data: Has Certificate : No
data: Has Access Token : Yes
data: User name : nico#XXXXXXX.onmicrosoft.com
data:
info: account show command OK
or simply:
azure account show --json | jq -r '.[0].tenantId'
or the new az:
az account show --subscription a... | jq -r '.tenantId'
az account list | jq -r '.[].tenantId'
I hope it helps
The tenant id is also present in the management console URL when you browse to the given Active Directory instance, e.g.,
https://manage.windowsazure.com/<morestuffhere>/ActiveDirectoryExtension/Directory/BD848865-BE84-4134-91C6-B415927B3AB1
Just to add a new method to an old (but still relevant question).
In the new portal, clicking the help icon from any screen and selecting 'Show Diagnostics' will show you a JSON document containing all your tenant information including TenantId, Tenant Name, and much, much more useful information
This answer was provided on Microsoft's website, last updated on 3/21/2018:
https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal
In short, here are the screenshots from the walkthrough:
Select Azure Active Directory.
To get the tenant ID, select Properties for your Azure AD tenant.
Copy the Directory ID. This value is your tenant ID.
Hope this helps.
Via PowerShell anonymously:
(Invoke-WebRequest https://login.windows.net/YOURDIRECTORYNAME.onmicrosoft.com/.well-known/openid-configuration|ConvertFrom-Json).token_endpoint.Split('/')[3]
Another way to get it from App registrations
Azure Active Directory -> App registrations -> click the app and it will show the tenant ID like this
You can run a simple curl call to get the tenant id of an azure subscription without any authentication.
make a curl call to :
https://management.azure.com/subscriptions/{subscription-id}?api-version=2015-01-01
The request fails but you will be able to get the tenant id from the response header. The tenant id is present in line followed by "WWW-Authenticate: Bearer authorization_uri="https://login.windows.net/"
you can use curl -v to show the response header.
As of now (06/07/2018), an easy approach would be running az account show in the Azure Cloud Shell (requires a Storage Account) in the Azure Portal.
--- Command ---
az account show
--- Command Output ---
{
"environmentName": "AzureCloud",
"id": "{Subscription Id (GUID)}",
"isDefault": true,
"name": "{Subscription Name}",
"state": "Enabled",
"tenantId": "{Tenant Id (GUID)}",
"user": {
"cloudShellID": true,
"name": "{User email}",
"type": "user"
}
}
Find more details on Azure Cloud Shell at Overview of Azure Cloud Shell | Microsoft Docs.
If you have installed Azure CLI 2.0 in your machine, you should be able to get the list of subscription that you belong to with the following command,
az login
if you want to see as a table output you could just use
az account get-access-token --query tenant --output tsv
or you could use the Rest API
Tenants - List | Microsoft Docs
Use the Azure CLI
az account get-access-token --query tenant --output tsv
In PowerShell:
Add-AzureRmAccount #if not already logged in
Get-AzureRmSubscription -SubscriptionName <SubscriptionName> | Select-Object -Property TenantId
One click answer:
open this URL:
https://portal.azure.com/#blade/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/Properties
If you have Azure CLI setup, you can run the command below,
az account list
or find it at ~/.azure/credentials
Step 1: Login to Microsoft Azure portal
Step 2: Search Azure Active directory
Step 3: Click on overview and find the tenant id from tenant information section
From Java:
public static String GetSubscriptionTenantId (String subscriptionId) throws ClientProtocolException, IOException
{
String tenantId = null;
String url = "https://management.azure.com/subscriptions/" + subscriptionId + "?api-version=2016-01-01";
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
Header[] headers = response.getAllHeaders();
for (Header header : headers)
{
if (header.getName().equals("WWW-Authenticate"))
{
// split by '"' to get the URL, split the URL by '/' to get the ID
tenantId = header.getValue().split("\"")[1].split("/")[3];
}
}
return tenantId;
}
According to Microsoft:
Find your tenantID: Your tenantId can be discovered by opening the following metadata.xml document: https://login.microsoft.com/GraphDir1.onmicrosoft.com/FederationMetadata/2007-06/FederationMetadata.xml - replace "graphDir1.onMicrosoft.com", with your tenant's domain value (any domain that is owned by the tenant will work). The tenantId is a guid, that is part of the sts URL, returned in the first xml node's sts url ("EntityDescriptor"): e.g. "https://sts.windows.net/".
Reference:
https://azure.microsoft.com/en-us/resources/samples/active-directory-dotnet-graphapi-web/
A simple way to get the tenantID is:
Connect-MsolService -cred $LiveCred #sign in to tenant
(Get-MSOLCompanyInformation).objectid.guid #get tenantID
Using Azure Portal:
Step1: Login to azure portal and search for Azure Active Directory and select it .
Step2: In the overview page of Azure Active Directory,find the tenant ID.
Using Azure CLI:
Use one of the commands az login, az account list, or az account tenant list. Find the TenantId property for each of subscriptions in the output from each command.
Using Powershell
Use the below command in powershell cmdlet.
Connect-AzAccount
Get-AzTenant
Reference:
Azure CLI
Get-Aztenant
I use following to get tenant id
az account show --query homeTenantId --output tsv
You can also get the tenant id, in fact all subscription details by logging into the url resources.azure.com
For AAD-B2C it is fairly simple. From Azure Portal with a B2C directory associated, go to your B2C directory (I added the "Azure AD B2C" to my portal's left menu). In the B2C directory click on "User flows (policies) directory menu item. In the policies pane click on one of your policies you previously added to select it. It should open a pane for the policy. Click "Properties". In the next pane is a section, "Token compatibility settings" which has a property "Issuer". Your AAD-B2C tenant GUID is contained in the URL.
The one working for me is this (after az login):
az account show |grep tenantId | awk {'print $2'} |tr -d '[:punct:]'
Go to the Azure portal > Azure Active Direcrory.
On the main screen, you should see your tenant ID.
xxx#Azure:~$ az ad sp create-for-rbac
Retrying role assignment creation: 1/36
{
"appId": "401143c2-95ef-4792-9900-23e07f7801e7",
"displayName": "azure-cli-2018-07-10-20-31-57",
"name": "http://azure-cli-2018-07-10-20-31-57",
"password": "a0471d14-9300-4177-ab08-5c45adb3476b",
"tenant": "e569f29e-b008-4cea-b6f0-48fa8532d64a"
}

Resources