I am trying to get the createdTime field for Azure resources through the Azure Resource Graph Explorer and it seems the Azure Resource Graph Explorer does not support this value. I cannot find it anywhere.
The odd thing is that the resources endpoint does have this value, so it does exist somewhere.
See the documentation of this endpoint here: https://learn.microsoft.com/en-us/rest/api/resources/resources/list (look at the $expand URI parameter). I tested this endpoint and it works. I can see the createdTime for all my resources within one subscription.
So why does the Resource Graph Explorer not have/expose this field?
Resource Graph Explorer provides browsable information about the Azure Resource Manager resource types and properties that you can query. Resource Graph Explorer also provides a clean interface for working with multiple queries, evaluating the results, and even converting the results of some queries into a chart that can be pinned to an Azure dashboard.
Some resource you can see creation Time such as below, but if you want to query you need to give detailed time. The article you provided is about resource list.
For Graph I don't know but using PowerShell or Rest you can use this sniped code.
$subscriptionID = "11111-111-1111-111111"
$resourceGroupName = "myResourceGroup"
#assumes you have an active Az CLI context authenticated to target subscription. Can also be done with Az PowerShell, but requires a different token retrieval method
$accessToken = az account get-access-token --query accessToken
#specify target API endpoint
$uri = "https://management.azure.com/subscriptions/$($subscriptionID)/resourcegroups/$($resourceGroupName)?api-version=2019-08-01&%24expand=createdTime"
$headers = #{
"Authorization" = "Bearer $($accessToken)"
}
#consume ARM endpoint
$rgInfo = Invoke-RestMethod -Uri $uri -Headers $headers -Method 'GET'
$creationDate = $rgInfo.createdTime
Code from michaeldroessler
Related
I'm trying to follow the guide outlined at this link to generate an access token for AKS for the system assigned managed identity.
The code snippet at the link is doing the following from an app service kudu console:
$resource = "https://graph.microsoft.com"
$endpoint = $env:IDENTITY_ENDPOINT
$header = $env:IDENTITY_HEADER
$apiVersion = "2019-08-01"
$headers = #{ 'X-Identity-Header' = $header }
$url = "$($endpoint)?api-version=$apiVersion&resource=$resource"
$response = Invoke-RestMethod -Method Get -Uri $url -Headers $headers
$response.access_token
Although this snippet works, the resource identifier varies depending on the resource for which you're requesting the access token. I'm not sure what resource value must be specified to get this for AKS. I have found it for the following, but not for AKS:
https://servicebus.azure.net
https://graph.microsoft.com
https://management.azure.com
https://database.windows.net
https://relay.azure.net
https://eventhubs.azure.net
Does anyone know what this ought to be for AKS?
Figured it out. Apparently after deploying AKS a new Microsoft generated enterprise application is created under your tenant called "Azure Kubernetes Service AAD Server" and has a universal GUID:
6dae42f8-4368-4678-94ff-3960e28e3630.
This should be used as the resource.
Surprisingly there's no mention on any Microsoft authored documentation regarding this. Stumbled across this on other sites.
Hope this helps someone else.
Some references:
Reference to this on github
Reference to this on related SO post
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.
I have been working on creating New Tenant from API or Command Line in Azure Active Directory and I could not find a way to do it.
I have been also using Azure GraphAPI but it doesn't support this.
Is there any way from command or API that I can use to automate creation of new tenants?
I have researched on google and stackoverflow, but I didn't find any way to do it from command or API.
and is there any plan of Microsoft to provide such API in future? (edited)
There's no public, documented or supported (by MSFT) API available for this. That being said you might try using the portal internal API with something like this:
Invoke-WebRequest -Uri "https://main.iam.ad.ext.azure.com/api/Directories" `
-Method "POST" `
-Headers #{
"Accept-Language"="en"
"Authorization"="Bearer <azure ad access token issued for aud=74658136-14ec-4630-ad9b-26e160ff0fc6>"
} `
-ContentType "application/json" `
-Body "{`"companyName`":`"<company name>`",`"initialDomainPrefix`":`"<initial domain prefix (the one that will be appended to onmicrosoft.com)>`",`"countryCode`":`"<iso (2 letter) country code>`"}"
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)
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.