Skip to content
adatum
  •  Learn Azure Bicep
  •  SCOM Web API
  •  About adatum
Azure Active Directory

Azure token from a custom app registration

  • 20/01/202220/01/2022
  • by Martin Ehrnst

There’s no secret you can get an Azure AD token and access API resources like Microsoft Graph, Azure Resource Manager (ARM), etc. It’s also pretty straightforward to authenticate a custom API using client credentials. In fact, I have written about how to do that previously where we accessed a custom API built on Azure Functions. Authentication-wise, I also wrote a post on how to access the Azure Monitor REST APIs using client credentials (app registration).

Get an Azure token with delegated user credentials from a custom API

The above examples are fine. But they both use a separate app registration for authenticating against our custom API, the Azure Function, and against ARM to access Azure Monitor. But what if I want to use my own, personal credentials instead of client credentials. For ARM resources, like Azure Monitor, Resource Graph, etc. You can do that already using Azure CLI, or the PowerShell example below.

Connect-AzAccount
Get-AzAccessToken -ResourceUrl "https://management.azure.com"

Wheater you use Az CLI or PowerShell, the output is similar to the above. you can decipher the token using jwt.io. And get a human-readable output.

Always be careful when using services like JWT.io Your token is after all your credentials and can give access to resources.


App registration expose an API

Instead of specifying ARM as we did above, you can also generate a token against your custom app registration using delegated permissions from Azure CLI or PowerShell. The secret lies in the “expose and API”, or more specifically, “Authorized client applications”.

To allow delegated access and the ability to receive a token from your custom app registration do the following

  • Make sure your user is allowed to access the app, you can add that in the enterprise app blade.
  • Create a scope under “expose and API”
  • Add client application(s) to the scope
    • Azure CLI client application ID: 04b07795-8ddb-461a-bbee-02f9e1bf7b46
    • Azure PowerShell client application ID: 1950a258-227b-4e31-a9cf-717495945fc2

Get access token from custom API using Azure CLI or PowerShell

Pull out your favorite shell and change you’re ResourceUrl from management.azure.com to your app id or URI. In my case, this is api://adatum-auth-test-app

After getting the token you can again use JWT.io and see the details. Pay attention to the appId and aud. AppId in this case is Azure PowerShell.

Final words

This post has been laying around in my draft for more than a year. But yesterday I got a question from a colleague about this and figured it was time to release it to the masses.

The reason I had it laying in drafts is that I am unsure of the supportability from Microsoft and the potential security vulnerability it may add to your services. However, keep that in mind and use the feature when needed.
If you want to learn more about application registrations, enterprise apps, and managed identities in general. Please read my other post about the topic.

Share this:

  • LinkedIn
  • Twitter
  • Reddit
Operations Manager

SCOM 1801 REST API Interfaces

  • 19/02/201819/02/2018
  • by Martin Ehrnst

For many years SCOM have delivered state of the art infrastructure monitoring. The platform itself is very flexible, but it has lacked an easy integration interface. This has now changed.

SCOM UnOfficial REST API

A year ago we needed an easier way to integrate monitoring data with non Microsoft products customer portals, CMDB etc. Some of these systems also needed the ability to trigger maintenance mode and create maintenance schedules. As an internal project with a very steep learning curve I started on a SCOM Web API. In May 2017 everyone on the Internet could see how poorly I knew C# as I pushed the whole project to GitHub (First commit).

Latest version now supports many new features and a lot of code changes.

 

SCOM Official REST API

As I follow Microsoft’s monitoring space closely I was very surprised when Jasper VanDamme started talking about a official SCOM REST API released with SCOM 1801. This was something never seen (by me) in the release notes and not talked about at all. If we had got this news when 1801 first announced I believe people had seen it as one of the big news along side HTML5 dashboards, which I understand is why the API now exists.

Being very passionate about SCOM and it’s possibilities despite being an old dinosaur, I feel this official API can open doors for many non SCOM admins creating very cool solutions. I was hoping this could happen to the one I created (and to some extent it have) but now we have a officialy backed SCOM API which is consistent and professional in every corner – future looks promising.

 

Resources

Official REST API Reference

Custom Dashboard Example

SCOM REST API on GitHub

 

Remarks

When I find the time to upgrade my labs to 1801 I will write a blog post dedicated to the new API. Please let me know if you have developed anything cool using either of the API’s available. I’m happy to check it out and provide feedback.

Share this:

  • LinkedIn
  • Twitter
  • Reddit
Azure

Resource health through Azure Rest API

  • 18/09/201725/11/2019
  • by Martin Ehrnst

As a part of a large monitoring project involving on prem, Azure and Office 365 I have started to explore the different methods on how to acquire all relevent data. Previously, I have written a post on how you authenticate against Microsoft’s partner center API which is a part of the same feasibility project.
Later down the road i will try to write a larger blog series on how we can monitor Microsoft Cloud and on-Prem resources. Hopefully it will be joyful…

This blog post will describe how you can use Powershell to authenticate and get availability status from all resource groups and their resources. If you’re not that interested in monitoring data, use this post as a guide on how to get started with the API and the rest is documented on the Azure API documentation pages.

High level overview:

  • Set up an Azure Active Directory Application to authenticate (not covered)
  • Build an authentication header with a token from Azure AD
  • Get all resource groups within a subscription
  • Get the availability of all resources within a resource group

 

Get Azure AD application token

After setting up/registering the application in Azure AD you will have to use the application ID and secret in order to generate an authentication token to use against Azure management Rest API’s. I have created a basic Powershell function you can use, including an example authentication header.


$result = Get-AADAppoAuthToken –ClientID <AzureAD APPLICATION ID> –ClientSecret <ClientSecret> –TenantId "test.no"
$AuthKey = "Bearer " + ($result.access_token)
$authHeader = @{
'Content-Type' = 'application/json'
'Accept' = 'application/json'
'Authorization' = $AuthKey
}

view raw

createAuthHeaderExample.ps1

hosted with ❤ by GitHub


<#
.SYNOPSIS
Function to connect to the Microsoft login OAuth endpoint and return an OAuth token.
.DESCRIPTION
Generate Azure AD oauth token.
You can specify the resource you want in the paramenter. Default is management.core.windows.net
Parts of this function is created from these examples: https://docs.microsoft.com/en-us/azure/monitoring-and-diagnostics/monitoring-rest-api-walkthrough
.PARAMETER ClientID
Azure AD application ID
.PARAMETER ClientSecret
Your application secret.
.PARAMETER TenantId
Your tenant domain name. test.onmicrosoft.com
.PARAMETER ResourceName
Specify if you are accessing other resources than https://management.core.windows.net
For example microsoft partner center would have https://api.partnercenter.microsoft.com
.EXAMPLE
Get-AADAppoAuthToken -ClientID 'xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' -ClientSecret <application secret> -TenantId "test.no" will return
token_type : Bearer
expires_in : 3600
ext_expires_in : 0
expires_on : 1505133623
not_before : 1505129723
resource : https://management.core.windows.net/
access_token : eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6IkhIQnlLVS0wRHFBcU1aaDZaRlBkMlZXYU90ZyIsImtpZCI6IkhIQnlLVS0wRHFBcU1aaDZaRlB
kMlZXYU90ZyJ9.eyJhdWQiOiJodHRwczovL21hbmFnZW1lbnQuY29yZS53aW5kb3dzLm5ldC8iLCJpc3MiOiJodHRwczovL3N0cy
.NOTES
v1.0
Martin Ehrnst 2017
#>
[Cmdletbinding()]
Param(
[Parameter(Mandatory = $true)]
[string]$ClientID,
[Parameter(Mandatory = $true)]
[string]$ClientSecret,
[Parameter(Mandatory = $true)]
[string]$TenantId,
[Parameter(Mandatory = $false)]
[string]$ResourceName = "https://management.core.windows.net/"
)
$LoginURL = 'https://login.windows.net'
#Get application access token
$Body = @{
grant_type = "client_credentials";
resource = $ResourceName;
client_id = $ClientID;
client_secret = $ClientSecret
}
Return Invoke-RestMethod –Method Post –Uri $LoginURL/$TenantId/oauth2/token –Body $Body
}

view raw

Get-AADAppoAuthToken.ps1

hosted with ❤ by GitHub

Get all resource groups and resources

Next we will grab all resource groups within a subscription, before looping through each resource group to get the individual resources.


#Loop through each reasource group and get all resources.
#Add everything to a hash table
$Groups = @()
foreach ($rg in $ResourceGroups) {
$ResourceGroupUri = "https://management.azure.com/subscriptions/$subscriptionID/resourceGroups/$rg/resources?api-version=$APIVersion"
$res = (Invoke-RestMethod –Uri $ResourceGroupUri –Method GET –Headers $authHeader).value
#Create array of all resources
$resources = @{}
$resources.Add($rg, $res)
#Add all resource groups and their resources to a hash table
$Groups += $resources
}

view raw

GetAllResorurcesWithinRG.ps1

hosted with ❤ by GitHub


#get all resource groups within a subscription
$APIVersion = "2017-05-10"
$subscriptionID = "xxxxxxxxxxxx-xxx-xxx-xxxxxxxxxx"
$RGURI = "https://management.azure.com/subscriptions/$subscriptionID/resourcegroups?api-version=$APIVersion"
$ResourceGroups = (Invoke-RestMethod –Uri $RGuri –Method GET –Headers $authHeader).value.name

view raw

GetAzureRG.ps1

hosted with ❤ by GitHub

Now that we have all resource group and all resources within we can use this to further get the resource health and availability. To be honest we don’t need to get RG before checking the resources it self, but as a starting point i find it very useful to have the resource groups and their resources available within my scripts.

 

Get the resource availability status

Now we have authenticated, grabbed all resource groups and their resources and it’s time to find our resource health. There are multiple ways on how to get this data, and we have to consider the methods we use. One limitation i hit pretty fast working with this is the number of subscription resource get requests, specified in the response header “x-ms-ratelimit-remaining-subscription-resource-requests: ” All limitations documentet,  here 

When you hit this limit every substantial requests is dropped. I have to rethink my whole monitoring scenario due to these limitations.

Get Resource health based on resource group

This let’s us get health state on all resources scoped to a resource group. If we reuse the data from previously (we have all resource groups within our subscription) we will get all resource group health this way.


availabilityState : Unavailable
summary : Your virtual machine is unavailable
detailedStatus : We're working to automatically recover your virtual machine and to determine the source of the problem. No additional action is required from you at this time.
reasonType : Unplanned
occuredTime : 2017-07-30T01:13:56Z
reasonChronicity : Persistent
reportedTime : 2017-09-12T11:27:42.3921293Z
resolutionETA : 2017-07-30T01:38:56Z

view raw

example-output

hosted with ❤ by GitHub


#get the health of the whole resource group
# Add each health status to a hashtable before output a complete table with all resource groups and their resource health
$resourceGroupHealth = @{}
foreach ($ResourceGroup in $ResourceGroups) {
#Set resource group name and use it in our url
$health = Invoke-RestMethod –Uri "https://management.azure.com/subscriptions/$subscriptionID/resourceGroups/$ResourceGroup/Providers/Microsoft.ResourceHealth/availabilityStatuses?api-version=2015-01-01" –Method GET –Headers $authHeader
$currentHealth = @{}
$currentHealth = @{
[string]"$ResourceGroup" = [object]$health
}
$resourceGroupHealth += $currentHealth
}
$resourceGroupHealth
#Explore the results
$resourceGroupHealth.item('ResourceGroup').Value.Properties

view raw

GetResourceGroupHealth.ps1

hosted with ❤ by GitHub

Other examples are to get availability by Resource and the entire subscription

 

 

 

Share this:

  • LinkedIn
  • Twitter
  • Reddit
Azure

Authenticate against Micrsoft Partner Center API using Powershell

  • 07/09/201719/12/2019
  • by Martin Ehrnst

Update 04.01.2019:
While the method described in this post still work. Microsoft are moving to what they call secure app model. Meaning that password grant is deprecated and you will need to use a refresh token model. I have written a new blog post, explaining the new model.

If you’re not familiar with the Microsoft Cloud Service Provider program it’s in short a program to easier let service providers manage their customers tenants and subscriptions within Azure and Office 365 from a centralized platform.

Apart from a very limited web portal it have a set of API’s and SDK’s to build your own solutions – wich I assume is prefered from Microsoft and the service provider. For a project I needed to authenticate against the REST API using Powershell and then retrieve some information about each tenant, who would have thought that could be so much work

Here’s what I said.

That’s fine, I will have it to you in an hour.

For your reference, this is the API I am working with: Partner Center Swagger

An hour later I did have authentication in place, but I was unable to retrieve any information from our customers. After digging through the documentation I found that the customer endpoints required “App + User Authentication” where I had only authenticated with AppId and App Secret.

After spending too much time decifer the C# examples on how you authenticate with app and user against the CSP Rest API i finally had a working Powershell function.

These are the steps required

  • Generate a token from Azure AD by calling https://login.microsoft.com/tenant-name/oauth/token
    • Specified with the resource you want to access (partner center api), client id, username and password, correct grant type and scope
  • Use the AAD token to authenticate against partnercenter/generatetoken and recieve a correct User + App jwt_token
  • Use the jwt token to further authenticate against endpoints you preffer

If you ever find your self in a situation where you need to authenticate against the CSP REST API as app + user, here is a function to do it.

Be aware that the function does require a credential object, but when you atuhenticate against AAD the password is decoded and sent in the post request.

Share this:

  • LinkedIn
  • Twitter
  • Reddit
Automation

Update: SCOM web API

  • 02/06/201715/11/2017
  • by Martin Ehrnst

Big updates:

I have made a lot of changes to the SCOM web API. As you can see from the picture above. Maintenance scheduling is added, which means you can create a new maintenance schedule in SCOM 2016. To the computer endpoints I have added the a possibility to get detailed information. This will list all related object to the server. Logical disks, network cards etc.

These are the API endpoints available at the moment:

Agents

Route Description
[GET] API/Agents Gets all agents
[GET] API/Agents/{id} Get a single agent

Alerts

Route Description
[GET] API/Alerts Gets all open alerts
[GET] API/Alert/{id} Get a single alert
[PUT] API/Alert Update the specified alert with resolution state, TicketId
[GET] API/Alert/{ComputerName} Get all alert from specific computer, use IncClosed=true to include open and closed alerts

Computer

Route Description
[GET] API/Computer/Windows Get all windows computers wit basic properties
[GET] API/Computer/Windows/{ComputerName} Get A single windows computers with basic properties
[GET] API/Computer/Windows/{ComputerName}/Detailed Get A single windows computers with hosted child objects
—— ——
[GET] API/Computer/Linux Get all Linux computers wit basic properties
[GET] API/Computer/Linux/{ComputerName} Get A single Linux computer with basic properties
[GET] API/Computer/Linux/{ComputerName}/Detailed Get A single Linux computers with hosted child objects

Maintenance

Route Description
[POST] API/ComputerMaintenance Put the specific computer object and all child in maintenance mode
[POST] API/ObjectMaintenance Put the specific monitoring object and all child in maintenance mode
[POST] API/MaintenanceSchedule Create a new maintenance schedule. SCOM 2016 ONLY

Object

Route Description
[GET] API/MonitoringObject/{id} Get a monitoring object and all child object

 

Examples

Create a new maintenance schedule by sending a post to /API/MaintenanceSchedule with a body including object id, start date and end date in UTC, optionally a comment.

#CREATE A MAINTENANCE SCHEDULE WITH TWO OBJECTS. Time in UTC

$body = @"
{
  "scheduleName": "new maintenance schedule",
  "id": "a43a5b09-5c32-8624-1427-73b8e1f05248",
  "StartTime": "2017-05-30T13:53:33.550Z",
  "EndTime": "2017-05-30T14:53:33.550Z",
  "comment": "TicketID"
}
"@


Invoke-RestMethod -Uri 'http://localhost:64049/API/MaintenanceSchedule' -Method Post -Body $body -UseDefaultCredentials -ContentType 'Application/json'

Get details/related object from a computer:

Invoke-RestMethod -Uri 'https://host/API/Computer/windows/computer.fqdn/Detailed' -UseDefaultCredentials

Which will return something like this. Notice the relatedObjectsCount and relatedObjects

Share this:

  • LinkedIn
  • Twitter
  • Reddit

Posts navigation

1 2

Top Posts & Pages

  • Azure Application registrations, Enterprise Apps, and managed identities
  • Automate Azure DevOps like a boss
  • Multi subscription deployment with DevOps and Azure Lighthouse
  • Creating Azure AD Application using Powershell
  • Azure token from a custom app registration
  • Azure AD authentication in Azure Functions
  • Script to add SCOM agent management group
  • How to move Azure blobs up the path
  • Track changes to Azure resources
  • Azure Bicep modules, variables, and T-shirt sizing

Tags

agent announcements api ARM authoring Automation azcopy Azure AzureAD Azure Bicep AzureDevOps AzureFunctions AzureLighthouse AzureManagement AzureMonitor AzureSpringClean Bicep Community CSP database EventGrid healthservicestore IaC Infrastructure as code Integrations logs management pack Microsoft Build Microsoft Partner monitoring MSIgnite MSOMS MSP nicconf Nordic Virtual Summit OperationsManager OpsMgr Powershell QUickPublish rest SCOM Serverless SquaredUP SysCtr system center

Follow Martin Ehrnst

  • Twitter
  • LinkedIn

RSS feed RSS - Posts

RSS feed RSS - Comments

Microsoft Azure MVP

Martin Ehrnst Microsoft Azure MVP
Adatum.no use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it. Cookie Policy
Theme by Colorlib Powered by WordPress
adatum
Proudly powered by WordPress Theme: Shapely.