I want to automate the creation of my application in Azure AD and get back the client id generated by Azure AD.
Are there PowerShell commandlets to do this? Is there some other means, like an API of doing this besides the management console?
Can you point me to an example?
Thanks!
There are a number of ways you can create an application in AAD Programatically. I will briefly cover two different ways you can go about doing this: PowerShell CMDLETs and the Graph API. In general, I would strongly reccommend using the Graph API for this.
PowerShell:
There are a few different modules running around that have the ability to create AAD Applications/Service Principals. If you need to create a new application object in your tenant, you can use Azure PowerShell to make the following call:
https://msdn.microsoft.com/en-us/library/mt603747.aspx
PS C:\> New-AzureRmADApplication -DisplayName "NewApplication" -HomePage "http://www.Contoso.com" -IdentifierUris "http://NewApplication"
If you need to create a service principal for your application in your tenant you can use Azure AD PowerShell:
https://msdn.microsoft.com/en-us/library/azure/jj151815.aspx
https://msdn.microsoft.com/en-us/library/azure/dn194119.aspx
New-MsolServicePrincipal -ServicePrincipalNames #("MyApp/Contoso.com") -DisplayName "My Application"
Graph API:
(recommended)
You can also create applications by making a POST to our Graph API:
https://msdn.microsoft.com/Library/Azure/Ad/Graph/api/entity-and-complex-type-reference#ApplicationEntity
We have samples that show how you can register and create an applicatoin to target the Graph API, and use the Graph Client Library to assist you in making the correct calls to the API:
https://github.com/AzureADSamples/WebApp-GraphAPI-DotNet
I hope this helps!
I'm a little late to the party - but I recently encountered this challenge too. Here are the relevant excerpts from my solution...
First you need to get the authentication token. For this you can use this handy function.
function GetAuthToken
{
param
(
[Parameter(Mandatory=$true)]
$TenantName
)
$adal = "${env:ProgramFiles(x86)}\Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Services\Microsoft.IdentityModel.Clients.ActiveDirectory.dll"
$adalforms = "${env:ProgramFiles(x86)}\Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Services\Microsoft.IdentityModel.Clients.ActiveDirectory.WindowsForms.dll"
[System.Reflection.Assembly]::LoadFrom($adal) | Out-Null
[System.Reflection.Assembly]::LoadFrom($adalforms) | Out-Null
$clientId = "1950a258-227b-4e31-a9cf-717495945fc2"
$redirectUri = "urn:ietf:wg:oauth:2.0:oob"
$resourceAppIdURI = "https://graph.windows.net"
$authority = "https://login.windows.net/$TenantName"
$authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority
$authResult = $authContext.AcquireToken($resourceAppIdURI, $clientId,$redirectUri, "Auto")
return $authResult
}
(borrowed from Paulo Marques https://blogs.technet.microsoft.com/paulomarques/2016/03/21/working-with-azure-active-directory-graph-api-from-powershell/)
You can then submit a POST request to the Azure Active Directory Graph API in order to create your application. However there is a little setup required.
# The name of this AAD instance
$global:tenant = "mycompany.onmicorosft.com"
$global:aadSecretGuid = New-Guid
$global:aadDisplayName = "azure-ad-displayname"
$global:aadIdentifierUris = #("https://contoso.com")
$guidBytes = [System.Text.Encoding]::UTF8.GetBytes($global:aadSecretGuid)
$global:aadSecret = #{
'type'='Symmetric';
'usage'='Verify';
'endDate'=[DateTime]::UtcNow.AddDays(365).ToString('u').Replace(' ', 'T');
'keyId'=$global:aadSecretGuid;
'startDate'=[DateTime]::UtcNow.AddDays(-1).ToString('u').Replace(' ', 'T');
'value'=[System.Convert]::ToBase64String($guidBytes);
}
# ADAL JSON token - necessary for making requests to Graph API
$global:token = GetAuthToken -TenantName $global:tenant
# REST API header with auth token
$global:authHeader = #{
'Content-Type'='application/json';
'Authorization'=$global:token.CreateAuthorizationHeader()
}
Now you can hit the Graph API.
$resource = "applications"
$payload = #{
'displayName'=$global:aadDisplayName;
'homepage'='https://www.contoso.com';
'identifierUris'= $global:aadIdentifierUris;
'keyCredentials'=#($global:aadSecret)
}
$payload = ConvertTo-Json -InputObject $payload
$uri = "https://graph.windows.net/$($global:tenant)/$($resource)?api-version=1.6"
$result = (Invoke-RestMethod -Uri $uri -Headers $global:authHeader -Body $payload -Method POST -Verbose).value
Once the response comes back, you can extract the configuration values you need.
# Extract configuration values
$keyObject = foreach($i in $result.keyCredentials) { $i }
# Tenant ID
$global:aadTenantId = Get-AzureRmSubscription | Select-Object -ExpandProperty TenantId
# Application object ID
$global:aadApplicationObjectId = $result | Select-Object -ExpandProperty objectId
# App ID / Client ID
$global:aadClientId = $result | Select-Object -ExpandProperty appId
# Application Secret/Key
$global:aadAppSecret = $keyObject | Select-Object -ExpandProperty keyId
I hope this helps somebody!
Microsoft has released a couple of additional PowerShell cmdlets to register an app and set credentials:
New-AzureRmADApplication
New-AzureRmADServicePrincipal
New-AzureRmRoleAssignment
Add-AzureADApplicationCredential
Please review their documentation:
https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-group-authenticate-service-principal
I've written some powershell scripts which will
Create AAD applications (thanks mainly to Matt's answer)
Create a Key Vault in Azure
Create a key in the Key Vault
Assign permissions to the key vault for the AAD applications
I know this is more than what you're asking for, but if, like me, you're interested in getting back the secret (aka key) from the application (the same one you add in the portal which you have to copy before never seeing it again), then the second script will allow you to explicitly send that in as part of the payload in a call to the Graph API. The script will save that to a file for you to refer to later.
The other scripts are not really what you're asking about, but you may still find them useful if you ever need to set up SQL Server to work with Azure Key Vault for TDE or column-level encryption.
Related
My application insight is enabled to Log analytics. I want to delete logs from specific application insight..
I want a PowerShell script where I can purge the data which is attached to workspace..
I want a PowerShell script where I can purge the data which is
attached to workspace..
Based on our research , we haven't find any Power Shell cmdlets that can be used to purge the data of application insights.
You can invoke this Rest API from PowerShell & you can send a POST request with a body that contains the Application Insights telemetry table we want to purge and the filter that we want to apply on those records.
Below are the steps to followed to invoke the rest api using the PowerShell & to purge data of a specific column :
To use this API , You need to create an app registration in AAD &
create client secret for that app registration.
you need to assign a role to your app in order to access the Application Insights resource.
Select the Application Insight resource (or directly select the
Subscription object if you want), click on Access Control (IAM) and
then add a role assignment.
create a new role assignment with Data Purger as the role and select your app registration (search for the
app name)
Here is the PowerShell script to Invoke the REST API:
Import-Module AzureRM.Profile
##pass the app registration details
$appId = "YOR_APPLICATION_ID"
$key = "YOR_CLIENT_SECRET"
$tenantId = "YOUR_AAD_TENANT_ID"
$subscriptionId = "YOUR_SUBSCRIPTION_ID"
$resourceGroupName = "YOUR_APPINSIGHTS_RESOURCE_GROUP_NAME"
$resourceName = "YOUR_APPINSIGHTS_INSTANCE_NAME"
# Create the authentication URL and get the authentication context
$authUrl = "https://login.windows.net/${tenantId}"
$AuthContext = [Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext]$authUrl
# Build the credential object and get the token form AAD
$credentials = New-Object Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential -ArgumentList $appId,$key
$result = $AuthContext.AcquireToken("https://management.core.windows.net/",$credentials)
# Build the authorization header JSON object
$authHeader = #{
'Content-Type'='application/json'
'Authorization'=$result.CreateAuthorizationHeader()
}
$URI = "https://management.azure.com/subscriptions/${subscriptionId}/resourceGroups/${resourceGroupName}/providers/Microsoft.Insights/components/${resourceName}/purge?api-version=2015-05-01"
$body = #"
{
"table": "customEvents",
"filters": [
{
"column": "timestamp",
"operator": "<",
"value": "2021-01-01T00:00:00.000"
}
]
}
"#
$purgeID=Invoke-RestMethod -Uri $URI -Method POST -Headers $authHeader -Body $body
It may take a while (e.g. 2-3 days) for the purge operation to get complete.
For more information , you can refer this blog or this reference SO thread.
im trying to write a backend program that will get all of Azure Security Center tasks (Recommendation) with no browser authorization involved.
As far as i saw, Graph API does not have an end point for Security tasks and the only endpoint i could find is https://learn.microsoft.com/en-us/rest/api/securitycenter/tasks/list which supports only Implicit flow authorization.
Is there a way to get authorization without using consent window in the browser, or to get the tasks via different endpoint?
You can use the below Powershell script which is using the REST API to get all the tasks:
$subscriptionId = "yoursubid"
$context = Get-AzContext
$profile = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile
$profileClient = New-Object -TypeName Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient -ArgumentList ($profile)
$token = $profileClient.AcquireAccessToken($context.Subscription.TenantId)
$authHeader = #{
'Content-Type' = 'application/json'
'Authorization' = 'Bearer ' + $token.AccessToken
}
$uri = "https://management.azure.com/subscriptions/$subscriptionId/providers/Microsoft.Security/tasks?api-version=2015-06-01-preview"
$response = Invoke-RestMethod -Uri $uri `
-Method Get `
-Headers $authHeader
$response.value | ConvertTo-Json
OR
You can directly use Azure CLI to get directly .
Command:
az security task list
Reference:
az security task | Microsoft Docs
Install the Azure Az PowerShell module with PowerShellGet | Microsoft Docs
Output for the above powershell script:
For those who will need this in the future,
it is possible.
It didnt work for me because i requested the bearer token from the wrong address, use the following url for the bearer token request:
https://login.microsoftonline.com/{tenantId}/oauth2/token
And NOT:
https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token
(This is the azure AD typical bearer token request url)
If you would rather not mess around with getting the bearer token (and you want to go the powershell route) you can also use Invoke-AzRestMethod
# Capture everything MDC can do from a REST API
$Capabilities = (Invoke-AzRestMethod -ApiVersion "2022-09-01" -ResourceProviderName 'Microsoft.Security').Content | ConvertFrom-Json
$Capabilities.resourceTypes
I have an azure function with Powershell core 6 environment create,
Wanted to run some of the MS graph powershell modules like "Get-IntuneManagedDevice | Get-MSGraphAllPages"
but this requires token which i tried to use "Connect-MSGraph" but when executed got the following error
Error:
Could not load type 'System.Security.Cryptography.SHA256Cng' from assembly 'System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.): Could not load type 'System.Security.Cryptography.SHA256Cng' from assembly 'System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.
can anyone help me in the fix or correct me if I am doing it wrong at any point.
Could you you please let's know if you have already created the application, secret key etc. which are needed to be created prior to access Graph API? I have created a blog explaining "How to create mailbox folders in Exchange Online mailboxes using Graph API and PowerShell". At the first portion, I am explaining the procedure to create the application in Azure tenant. Please check that. Hope, it helps you
Create Custom Folder in Exchange Online Mailboxes using Graph API using Windows PowerShell
Thanks,
Manu
How about the following way:
Downlead the latest release of Intune Power Shell SDK from the following GitHub repository
https://github.com/Microsoft/Intune-PowerShell-SDK/releases
Unblock the code
Import the module in PowerShell
Import-Module .\Microsoft.Graph.Intune.psd1Import-Module .\Microsoft.Graph.Intune.psd1
Connect MS Grpah
Connect-MSGraph -AdminConsent
Try the In-Tune managed devices connection (Get-IntuneManagedDevice | Get-MSGraphAllPages)
Thanks,
Manu
For this problem, I don't know how to run Get-IntuneManagedDevice with token in azure powershell function. But I can provide a workaround below for your reference(use rest api to get the same result in azure powershell function which you expected).
1. Open fildder and run the command Get-IntuneManagedDevice in powershell, we can see the command request the microsoft graph api in the backend. The api is https://graph.microsoft.com/v1.0/deviceManagement/managedDevices and this page is its document (you do not need to do this step).
2. We need to add the permission for your app registered in azure ad.
After add the permission, don't forget grant admin consent for it.
3. We can find the graph api just support Delegated permission type but not support Application permission type according to the document.
So we can't use client credential as grant type to get the access token(we can't just use secret key to get access token) as you mentioned in the comments above. We need to request the access token by password grant type, so use the command below to get access token:
$AppId = 'xxx'
$AppSecret = 'xxx'
$Scope = "https://graph.microsoft.com/.default"
$TenantName = "xxx"
$username = "xxx"
$password = "xxx"
$Url = "https://login.microsoftonline.com/$TenantName/oauth2/v2.0/token"
Add-Type -AssemblyName System.Web
$Body = #{
client_id = $AppId
client_secret = $AppSecret
scope = $Scope
username = $username
password = $password
grant_type = 'password'
}
$PostSplat = #{
ContentType = 'application/x-www-form-urlencoded'
Method = 'POST'
Body = $Body
Uri = $Url
}
$Request = Invoke-RestMethod #PostSplat
$Request.access_token
4. In step 1 we know the command Get-IntuneManagedDevice request the graph api in the backend, so we just need to request the graph api and then we can get the result.
$Uri = "https://graph.microsoft.com/v1.0/deviceManagement/managedDevices"
$Header = #{
Authorization = "$($Request.token_type) $($Request.access_token)"
}
$result = Invoke-RestMethod -Uri $Uri -Headers $Header -Method Get -ContentType "application/json"
$result.value
Hope it helps~
Short Scenrario: A muti tenant front end javascript (React.JS) Web Application calls a multi tenant ASP.NET Core 2.2 WebAPI from the browser.
Authentication:
ADAL.js in the front end app takes care of getting a token from either AzureAD1 or AzureAD2 or AzureAD3... when the User signs-in (based on the User's original Azure Active Directory).
The User gives consent to the front end Web App (scope: Sign in and read user profile) which is delegated to the WebAPI too. (meaning the user does not need to consent to the WebAPI as well)
The front end Web App calls the WebAPI with the bearer token to get the resources.
Problem: I must automate the deployment of a new environment. And set the manifest file accordingly (It's a SaaS solution)
In the manifest file I need to expose the WebAPI for the client application (https://learn.microsoft.com/en-us/azure/active-directory/develop/quickstart-configure-app-expose-web-apis#expose-a-new-scope-through-the-ui)
Setting "knownClientApplications" is not enough (due to previously described delegation)
The new v2 endpoint (https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-overview) has a new App Registration feature. The old one is called "Legacy" now and will be deprecated starting May 2019.
In the Azure Portal need to expose the API and add the front end WebApp as an "Authorized cient applications".
This step will add a new object in the manifest file:
"preAuthorizedApplications": [
{
"appId": "guid",
"permissionIds": [
"guid"
]
}
],
But it's still not available throuh PowerShell! (https://learn.microsoft.com/en-us/powershell/module/azuread/set-azureadapplication?view=azureadps-2.0)
How can I add this "preAuthorizedApplications" section into the manifest file using Azure PowerShell? Why is it available in the portal but not in PS yet? It's the other way around usually...
08-05-2019 Update based on the answer:
I am getting the access token via a Service Principal:
$adTokenUrl = "https://login.microsoftonline.com/$TenantId/oauth2/token"
$resource = "https://graph.windows.net/"
$body = #{
grant_type = "client_credentials"
client_id = "$ServicePrincipalId"
client_secret = "$ServicePrincipalKey"
resource = "$resource"
}
$response = Invoke-RestMethod -Method 'Post' -Uri $adTokenUrl -ContentType "application/x-www-form-urlencoded" -Body $body
$token = $response.access_token
According to the docs: https://learn.microsoft.com/en-us/graph/api/application-update?view=graph-rest-beta&tabs=cs
The Service Principal should have at least Application.ReadWrite.OwnedBy, and most Application.ReadWrite.All privileges.
Should I ask our AAD admin to grant the below rights to the Service Principal?
08-05-2019 Update 2: Service Principal has been granted with ALL of the highlighted rights above.
Attempt 1:
Step 1: getting an access_token via the Service Principal (Owner of the Api app to be updated)
$adTokenUrl = "https://login.microsoftonline.com/$(TenantId)/oauth2/token"
$resource = "https://graph.microsoft.com/"
$body = #{
grant_type = "client_credentials"
client_id = "$(ServicePrincipalId)"
client_secret = "$(ServicePrincipalKey)"
resource = "$resource"
}
$response = Invoke-RestMethod -Method 'Post' -Uri $adTokenUrl -ContentType "application/x-www-form-urlencoded" -Body $body
$token = $response.access_token
Step 2: using this access_token, building up my PATCH request as per Md Farid Uddin Kiron's suggestion, and
Result: The remote server returned an error: (403) Forbidden.
09-05-2019 Update 3: After some kind and detailed explanation and guidance, I got this to work and getting HTTP 204 for my Postman request. Only thing left is to integrate this steps into my pipeline.
See accepted answer. It works. If someone has the same issue,
please read the other answer from Md Farid Uddin Kiron.
If you want to avoid calling directly the graph API (maybe you are in an azure pipeline using a Service Connection and don't have access to the credentials) you can do this :
$AppName = << WebApp >>
$preAuthorizedApplicationsAppId = <<GUID>>
# Get the application and delegated permission to pre-authorize
$appRegistration = Get-AzureADMSApplication -Filter "displayName eq '$AppName'"
$oauth2Permission = $appRegistration.Api.OAuth2PermissionScopes | Where-Object {$_.Value -eq $AppName -and $_.Type -eq 'Admin'}
# Build a PreAuthorizedApplication object
$preAuthorizedApplication = New-Object 'Microsoft.Open.MSGraph.Model.PreAuthorizedApplication'
$preAuthorizedApplication.AppId = $preAuthorizedApplicationsAppId
$preAuthorizedApplication.DelegatedPermissionIds = #($oauth2Permission.Id)
$appRegistration.Api.PreAuthorizedApplications = New-Object 'System.Collections.Generic.List[Microsoft.Open.MSGraph.Model.PreAuthorizedApplication]'
$appRegistration.Api.PreAuthorizedApplications.Add($preAuthorizedApplication)
# Update the Application object
Set-AzureADMSApplication -ObjectId $appRegistration.Id -Api $appRegistration.Api
This answer comes from this GitHub issue.
You are right, seems there is something faultiness exists in AzureAD powershell module. That not works for me too .
If you want to modify your app manifest using powershell to add "preAuthorizedApplications" section, you can try the powershell script below.
I have tested on my side and it works for me.
In theory, I have called Microsoft Graph API to modify the app manifest . If you have any further concerns, please feel free to let me know.
$AdAdminUserName = "<-your Azure ad admin username ->"
$AdAdminPass="<-your Azure ad admin password ->"
$AdAppObjId = "<-your app obj id->"
$AdPreAuthAppId = "<-the app that need to be pre authed ->"
$AdAppScopeId = "<-your app scope id->"
$tenantName = "<-your tenant name->"
$body=#{
"grant_type"="password";
"resource"="https://graph.microsoft.com/";
"client_id"="1950a258-227b-4e31-a9cf-717495945fc2";
"username"=$AdAdminUserName;
"password" = $AdAdminPass
}
$requrl = "https://login.microsoftonline.com/"+$tenantName+"/oauth2/token"
$result=Invoke-RestMethod -Uri $requrl -Method POST -Body $body
$headers = New-Object 'System.Collections.Generic.Dictionary[String,String]'
$headers.Add("Content-Type","application/json")
$headers.Add("Authorization","Bearer " + $result.access_token)
$preAuthBody = "{`"api`": {`"preAuthorizedApplications`": [{`"appId`": `"" + $AdPreAuthAppId + "`",`"permissionIds`": [`"" + $AdAppScopeId + "`"]}]}}"
$requrl= "https://graph.microsoft.com/beta/applications/"+$AdAppObjId
Invoke-RestMethod -Uri $requrl -Method PATCH -Body $preAuthBody -Headers $headers
Note: ROPC is not safe as Microsoft does not recommend to use that. It also does not allow to use MFA that is why it is little
dangerous.
Some additions to another reply.
Actually, in AzureADPreview powershell module, there is a parameter -PreAuthorizedApplications for Set-AzureADApplication. But neither the cmdlet help nor the documentation page has been updated to detail all these, it was also mentioned here.
I am not sure the parameter will work or not, per my test, I always get a bad request error. Even if I call the Azure AD Graph API, I get the same error. The command Set-AzureADApplication essentially calls the Azure AD Graph API, so if the parameter works, it will also work for the API. Also, in the AAD Graph doc, there is no such property. According to the test result, the parameter seems not to work currently. (not sure, if there is something wrong, please correct me)
I got this error too using client_credentials type to get access_token to call that API even though I granted all Microsoft Graph API and AAD API application related permissions. It is really weird.
However , using password flow to get access token under Azure AD admin account will be able to call this API successfully :
Update
You could get your client id and client secret by below steps
Go to azure portal on azure active directory menu see the screen
hot below:
Once you select azure active directory you would see App
registrations click on that. Then select your application. See the below picture
On your apllication you would see the client id, tenant id and
client secret which marked on the screen shot below:
If you still have any concern please feel free to share. Thank you and happy coding!
to resolve token issue I did like this(if you have az subscription owner, in this case you can get token which allows to update aad owned application properties without aad admin login and password). After az login by subscription owner:
$msGraphAccess = az account get-access-token --resource "https://graph.microsoft.com |
ConvertFrom-Json
$accessToken = $msGraphAccess.accessToken
$headers = New-Object 'System.Collections.Generic.Dictionary[String,String]'
$headers.Add("Content-Type", "application/json")
$headers.Add("Authorization", "Bearer " + $accessToken)
What I want is simple but I have not found a clear answer.
I have a simple console app and all I want to do is get all the users in my Azure AD using the new GRAPH API. All the examples I have require the program login (OAuth?). I don't want that. I want to give the code the user/pw and simply start calling the methods.
Whenever you have a user physically sitting at the device, your best bet, by far, is to invoke the full sign-in flow. Not only does keep an admin's credentials from being exposed, but it also allows the user to change password if needed, invoke multi-factor authentication, etc.
However, there are some scenarios where you want an entirely unsupervised service running on a completely secure and trusted machine. (Known as a "confidential client" in OAuth 2.0.) This can be achieved with the OAuth 2.0 Client Credentials Grant flow, which uses only the application's credentials to authenticate. This is illustrated in Service to Service Calls Using Client Credentials.
Using ADAL, this flow is invoked by using either AuthenticationContext.AcquireToken(String, ClientCredential) (where your credential is an password credential--a string), or AuthenticationContext.AcquireToken(String, ClientAssertionCertificate) (where your credential is a certificate that you use to sign an assertion). There is a .NET (C#) sample for each of these on the Azure AD samples for daemon applications:
Calling web APIs in a daemon or long-running process
Authenticating to Azure AD in daemon apps with certificates
Using PowerShell and certificate authentication, it would look something like this:
$appId = "<app client ID>"
$resource = "https://graph.windows.net" # (or other resource URI)
$tenantId = "<domain name or ID>"
$certThumbprint = "<certificate thumbprint>"
# Get locally-installed cert by thumbprint
$x509cert = Get-ChildItem "Cert:\LocalMachine\My" | ? { $_.Thumbprint -eq $certThumbprint } | Select-Object -First 1
# Get access token using ClientAssertionCertificate
$authority = "https://login.microsoftonline.com/$tenantId"
$creds = New-Object Microsoft.IdentityModel.Clients.ActiveDirectory.ClientAssertionCertificate $appId, $x509cert
$authContext = New-Object Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext $authority
$authResult = $authContext.AcquireToken($resource, $creds)
# Make Graph API request to list all users
$header = #{
"Authorization" = "Bearer $($authResult.AccessToken)"
"Content-Type" = "application/json"
}
$result = Invoke-RestMethod -Method Get -Headers $header -Uri "https://graph.windows.net/$tenantId/users?api-version=1.6"
($result.Content | ConvertFrom-Json).value
You will need to ensure your application is registered in Azure AD, and has the minimum required application permissions for what you're trying to do (and not more than that, to limit your exposure if the app's credentials were to be compromised). For example, if your application only needs to read directory data (e.g. to find a user by email address), you would set the permissions like this:
Here is the PowerShell script I wrote.
# Adding the AD library to your PowerShell Session.
Add-Type -Path 'C:\Program Files\Microsoft Azure Active Directory Connect\Microsoft.IdentityModel.Clients.ActiveDirectory.dll'
# This is the tenant id of you Azure AD. You can use tenant name instead if you want.
$tenantID = "<the tenant id of Azure AD>"
$authString = "https://login.microsoftonline.com/$tenantID"
# Here, the username must be MFA disabled user Admin at least, and must not be a live id.
$username = "<the username of the AD's Admin>"
$password = "<the password of the above user>"
# The resource URI for your token.
$resource = "https://graph.windows.net/"
# This is the common client id.
$client_id = "1950a258-227b-4e31-a9cf-717495945fc2"
# Create a client credential with the above common client id, username and password.
$creds = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.UserCredential" `
-ArgumentList $username,$password
# Create a authentication context with the above authentication string.
$authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" `
-ArgumentList $authString
# Acquire access token from server.
$authenticationResult = $authContext.AcquireToken($resource,$client_id,$creds)
# Use the access token to setup headers for your http request.
$authHeader = $authenticationResult.AccessTokenType + " " + $authenticationResult.AccessToken
$headers = #{"Authorization"=$authHeader; "Content-Type"="application/json"}
# Get the users.
Invoke-RestMethod -Method GET -Uri "https://graph.windows.net/$tenantID/users?api-version=1.6"
If you are using C#, it would be really similar, because my script is actually translated from C# code. For other Programing language, there are similar APIs in the corresponding Azure SDK. If not, you might consider using OAuth2.