How to get the azure account tenant Id? - azure

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"
}

Related

Azure MS Graph Claim Mapping Policy Powershell

I am a little confused with the MS Graph article[Vague] related to Claim Mapping Policy. I am trying to create claims using PowerShell. used below format to create new claims map getting error
New-MgPolicyClaimMappingPolicy : Property definition has an invalid value.
Help is needed Here!!!
$policymap=[ordered]#{
definition=#(
#"
{
"claimsMappingPolicy" :
{
"claimsSchema":[
{
"source":"user"
"id":"assignedrikes"
"samlclaimtype":"https://aws.amazon.com/SAML/Attributes/Role"
},
{
"source":"user"
"id":"assignedrikes"
"samlclaimtype":"https://aws.amazon.com/SAML/Attributes/RoleSessionName"
}
]
}
}
"#
)
displayname="Test"
isorganizationdefault=$false
}
New-MgPolicyClaimMappingPolicy -BodyParameter $policymap
New claims map getting error New-MgPolicyClaimMappingPolicy
This error may occur if you are using incorrect format samlclaimtype instead of using MgPolicyClaimMappingPolicy, make sure to install Azure AD Preview while running below script.
Please check below few workarounds:
I installed Azure AD Preview module and created claims using below script.
Connect-AzureAD
New-AzureADPolicy -Definition #('
{
"ClaimsMappingPolicy":
{
"Version":1,"IncludeBasicClaimSet":"true",
"ClaimsSchema": [{"Source":"user","ID":"extensionattribute1","SamlClaimType":"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/vikram","JwtClaimType":"vikram"}]
}
}') -DisplayName "vikram" -Type "ClaimsMappingPolicy"
Result:
Try to add service principal and check if it is succeeded or not.
For service principal ID, Go to Azure Portal -> Enterprise Applications -> Your Web API -> object ID like below:
Add-AzureADServicePrincipalPolicy -Id <ObjectId of the Web API ServicePrincipal> -RefObjectId <ObjectId of the Policy>
Get-AzureADServicePrincipalPolicy -Id <ObjectId of the Web API ServicePrincipal>
To assign value to that claim, login to Microsoft Graph Explorer with your tenant admin account and run below script. ***This completes the development of your claims mapping successfully. ***
PATCH https://graph.microsoft.com/beta/me
{
"onPremisesExtensionAttributes":
{
"extensionAttribute1": "vedha"
}
}
Now Go to Azure Portal -> Azure Active Directory -> App registrations -> Your App -> Manifest to make your claims to accept as true like below:
Then, Go to Expose an API under manage edit your Application ID URI pattern like https://<yourTenantDomain> instead of default api://<GUID>, and save.
Generate access token and you can see that custom claim you created in the decoded token. To decode the token, you can use jwt.ms website

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();

How do you grant api permission of user_impersonation {scope} to another azure ad app

I am trying to grant user_impersonation = scope rights to Azure AD App programatically .But unfortunately i am not getting the correct GUID of user_impersonation. I took it from another application manifest file but it seems it changes every time. Can someone assist me here.
I tried the below command to grant access
az ad app permission add --id --api --api-permissions user_impersonation=Scope
I have the way around by using below approach, Please suggest if it is right
$sp = Get-AzureADServicePrincipal -ObjectId "ObjectId"
$sp.Oauth2Permissions | select Id,AdminConsentDisplayName,Value
For this you get the below :
Id AdminConsent DisplayName Value
fb5a-c16f-4e30-49cd-ad2b3 Access ddudisplay user_impersonation
As soon as you have highlighted ID then you can put in the below command
az ad app permission add --id "appid" --api"resourceid" --api-permissions fb5a5asncdb-c16f-4e30-49cd-ada072b3=Scope
and viola it works.

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);

Grant an existing B2C app access to graph API

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

Resources