Automatically renew Android enrollment tokens using Power Automate

This month’s post is a continuation of automation with Intune data using Power Automate and Graph. When managing Android devices utilizing Device Owner enrollment (i.e. Android Enterprise) there are options for enrollment, NFC, QR Code, and Zero Touch. Each enrollment option requires an enrollment token as well and those are displayed in the Microsoft Endpoint Manager (MEM) admin center. With Android Device Owner dedicated (i.e. kiosk) enrollments, MEM Intune provides the option to create enrollment profiles where each has their own enrollment token. Organizations may choose to create multiple profiles for various reasons, however enrollment profiles may be utilized to automatically to add devices to Azure AD dynamic groups. This makes management of devices and targeting policy/apps seamless.

One point of feedback I’ve received is about the token lifetime of 90 days for Device Owner dedicated enrollment profiles. When an enrollment token expires no new devices may be enrolled until the token lifetime is extended (existing enrolled devices are not impacted). Token extensions may be completed in the MEM admin center or through PowerShell. However, why not automate the process? This is exactly what I do in this month’s post.

Let’s get started

Requirements

  • Microsoft Endpoint Manager Intune
  • Microsoft Power Automate (aka Microsoft Flow)
  • Azure Active Directory

Description of the process

The process of renewing token when they near their expiration is as follows:

  1. Introduce a recurrence trigger where the Flow processes every day.
  2. Set a timeframe to look for when tokens are about to expire.
  3. Make a graph call through HTTP.
  4. Parse the JSON that comes from the output of the Graph call.
  5. Look for any tokens that expire within 10 days.
  6. If successful, extend the token for another 90 days.
  7. Make another Graph call and parse JSON to get the tokens that were extended.
  8. Send a notification of which tokens were extended to Teams.

Here is the entire Flow we’ll walk through:

Power Automate

Log into Power Automate, i.e. flow.microsoft.com and create a new Flow.

Scheduled run

Insert a Recurrence trigger and modify to run every day at a specific time.

Add to time

We need to set a timeframe for when the token is set to expire. I chose 10 days, and later on we’ll use this value to look and see if tokens are set to expire within 10 days.

Register an app with Azure AD

To make Graph calls we need to register an app in Azure AD and grant it the following delegated permissions: DeviceManagementConfiguration.ReadWrite.All

We can pull all the information to build the query from: https://docs.microsoft.com/en-us/graph/api/intune-androidforwork-androiddeviceownerenrollmentprofile-createtoken?view=graph-rest-beta

POST https://graph.microsoft.com/beta/deviceManagement/androidDeviceOwnerEnrollmentProfiles/{androidDeviceOwnerEnrollmentProfileId}/createToken

Content-type: application/json

Content-length: 35

{

“tokenValidityInSeconds”: 7776000

}

This API is under /beta and may change, please make note of this.

Add a Redirect URI, I pull this from the connector I created in a previous post:


Create a client secret to utilize in authentication:

Grant proper API permissions:


Use Graph to query for all Android enrollment tokens

Add an HTTP action and configure as shown in the image below. This is a GET method.

Refer to the Azure AD app registration completed in the previous step to fill in Client ID and Secret.

Add a Parse JSON action so we can utilize the values that come back in the GET method.

Choose the “Body” of the HTML action and for the Schema, make a Graph call using Graph Explorer by doing the following:

Add a Condition action (this will turn into a Apply to each automatically)

In the first field add tokenExpirationDateTime (this will trigger the Apply to each action) > is less than or equal to > in the second field add “Add to time” output from the action created in the beginning of this post:

Add an “And” in the condition and in the first field add tokenExpirationDateTime > is greater than or equal to > and in the second field choose utcNow() from Expression.

What the condition is doing is checking to see if the date of the token expiration falls within 10 days, if not do nothing, if yes, we extend the token with actions under “If yes” which I cover next.

Extending the Android enrollment token

The fist step if the condition is true is to update the tokens that expire within 10 days. I created a custom connector as this is a POST method and I found the best method is to create a connector with variables that are exposed in the connector I can add in.

To create a connector, in Power Automate expand Data and select Custom connectors and select new create from blank. I import from Postman and if you’re interested in how to do that, please refer my previous post on the topic.

Security tab

Use the same Client ID and secret from the Azure AD app registration step completed earlier. For the Resource URL, type in https://graph.microsoft.com (the redirect URL will auto generate once Update connector is selected, the URL should match what’s in the Azure AD app registration):

Definition tab

Add a “New action” and add some details as shown in the image below, the Operation ID is something you’ll make up:

For the Request, select import from sample, select POST, add in the URL below, and add in the JSON in the body and select Import:

https://graph.microsoft.com/beta/deviceManagement/androidDeviceOwnerEnrollmentProfiles/{ID}/createToken

We now have the parameters needed for the POST method (which will extend the token for x number of day, e.g. 90 days):

Select Update connector and test the connector by creating a new connection and filling in the blank fields with static data. ID will be the ID of a token.

Back in the Flow, add an action and select custom and choose the new connector. ID will be the ID from the JSON output and tokenValidityInSeconds is self-explanatory, 7776000 which translates to 90 days.

Next we want to validate the tokens that were extended by calling Graph. We do this by adding two actions, an HTTP action and a Parse JSON action.

The HTTP action is identical to the one we created earlier, however append it by adding the ID of the token from the dynamic content list. Use the same process for Parse JSON as we did in the previous step as well. This step will only pull the tokens that were extended.

Lastly I’d like to know when enrollment tokens were extended so I send messages to Teams.

The reason why we query for the tokens that were extended in the step above is because we need to utilize that output to populate the Teams messages.

I have a couple tokens I set to expire in 5 days (in fact you can set any expiration date within 90 days directly from the MEM admin center if needed. It’s good for testing as well.):

I ran the Flow and here are the results posted to Teams, however you can send to email, SMS, SharePoint, etc. if you prefer, just look for the diffrent templates in Power Automate:

And in the Intune console:

One last item

If you’d rather view and extend Tokens by hand in the UI, you can do so by selecting Filter then Inactive which shows all expired and active tokens.

That’s it, utilizing Power Automate and Microsoft Graph we have automated extending Android enrollment token expiration dates and posted the results to Teams.

Microsoft Endpoint Manager Intune, Power Automate, and Microsoft Graph

One of my passions is working with customers and I’m fortunate to be able to speak with customers every day. Another passion of mine is automating tasks. A piece of customer feedback I receive is how to automate certain processes using the data within Intune, Microsoft 365, and 3rd party services.  Currently organizations may automate programatically by using the Microsoft Graph, however if you’re not familiar with using PowerShell or a developer it may be difficult to create a solution in the timeframe you need it by. Fortunately, there are Intune Graph samples available and if you’re intersted in viewing and utilizing the samples please visit: https://github.com/microsoftgraph/powershell-intune-samples.

Additionally, and the goal of this post, Microsoft Power Automate provides a robust set of templates and connectors to automate processes across Microsoft 365 and many other solutions.

For this post, using Microsoft Graph and Power Automate, I have automated end user email notifications after an end user has enrolled a device. The Power Automate (aka Flow) runs every hour and will send a mail to the end user who enrolled the device within the hour (or timeframe of your choice) of the last time the Power Automate process ran. From a security and user awareness perspective, an organization may want to notify users after a device enrollment completes, and if it wasn’t the user who actually enrolled the device, they could report it to their security and MDM teams.

Let’s get started

Requirements

  • Azure Active directory
  • Intune
  • Power Automate
  • SharePoint Online
  • Postman

Azure Active Directory

Register an application in Azure and creating a Power Automate connector for Microsoft Graph

We need to do several things to register an app in Azure AD and create a Power Automate connector, however registering an app in Azure AD and granting it permissions is several steps as is creating a Power Automate connector (because I use Postman to create the auth flow and query to Graph then save it out and import it to Power Automate as a custom connector). So to keep this focused on the automation piece, I found an individual online who published the following video who has a great walk through of how to do this in the first 30 minutes: https://www.bing.com/videos/search?q=graph+api+microsoft+flow&docid=608006419082446884&mid=DDFFFEB586D6DA665B5DDDFFFEB586D6DA665B5D&view=detail&FORM=VIRE

I recommend going through the steps in the video above and supplementing the perms and Graph call with the following:

To access Graph in Power Automate we to register a new application in Azure Active Directory so we can use it to make Graph calls to Intune. Once the application is registered we need to provide it the following application permissions to access Intune device objects:

Note: I have more perms granted than needed for this particular process, however the three above should be enough:

We also need to create a client secret and save it for later use in Postman:

Postman and Graph Explorer

If you don’t have Postman you can download it from: https://www.postman.com/downloads/

Use Graph explorer to come up with the query you’d like to use by visiting: https://developer.microsoft.com/en-us/graph/graph-explorer For this post I’m pulling all the managed devices from Intune: https://graph.microsoft.com/v1.0/deviceManagement/managedDevices/

For reference, here is the authorization for the Flow connector collection I created in Postman.

You’ll save the collection out and import as a custom connector in Power Automate. Refer to the video above and it walks you through all this minus the uniqness of my query and app.


SharePoint Online

We need a method to look up when the last time the Flow ran and to do this I store one list item in a SharePoint list. The item I store is just the date, however what I really care about is the created time the list item was created because I call that in the Flow and compare it to when the devices were last enrolled. For example, if the Flow ran on 2020-04-03T20:22:15Z, the date is stored in SharePoint and for any device registered after that time, an email will be sent to the end user. It’s a simple process, however it works well.

The following is my SharePoint Online list where I store a formatted date in the Title fiel, however it really doesn’t matter what is stored in the Title field as the Flow looks for the “created” date for the single item. After the flow completes, I have a process in Flow that deletes the record and adds a new one so the next time it runs it has new date to reference.


Power Automate

At this point you should have an app registered with Azure AD, a connector created in Power Automate, and a SharePoint list to reference.  Now we can move on to the next step.

Let’s create the Power Automate process now:

In Power Automate select Create, name it, and as the trigger select “Manually trigger a flow”. We need a trigger, and for testing I recommend creating the Power Automate process with a manual trigger. When you’re ready to go live, delete the trigger and replace it with the Recurrence trigger, more on this later.

Here’s the Flow in it’s entirety, however I break it down in the next few steps:

First step in the Flow, beyond the manual trigger, is pulling the item from the SharePoint list.  Do to this, add a new action and search for SharePoint the select “Get items”. I’m not doing anything special in Get items as I’m just looking for that one item in the list so there is no need to limit or filter items:

Next add another action, select “Custom” and select the connector you created earlier:

Now we need to parse the JSON that was returned from the custom action above. Do this by adding an action and search for Parse JSON, then add it. As you can see in the image below I have a perfectly formatted JSON output, however this needs to be generated. To do this select “Generate from sample” and go to either Graph explorer or Postman and copy all the JSON query output and paste into the sample payload.  Once you select done in the sample payload prompt, it will format properly and show something identical to what I have in the image below (provided you’re making the same Graph call).  You can also remove attributes from the JSON if you don’t want to show them in the dynamic content.

Next I want to select only devices that have a UPN because we can’t send email if there is no UPN to sent it to.  If the device record has a UPN and was created after the timestamp we stored in SharePoint, the user will receive a mail (sample mail shown later on in this post). To do this add an action and search for “Select” and add it. In the “From” field add the value from the Parse JSON step above, and in the Map section, select the txt icon on the far right then choose userPrincipleName from the dynamic list:

This next step is a cascade of actions so pay close attention please:

  • Add an “Apply to each” action and select the Parse JSON value (just like you did in the Select step above).
  • Now add an embeded “Apply to each” action and add the value from the SharePoint step above.

  • Add an embedded “Condition” action (this is where we compare dates), and in the first box find and select “created” from the SharePoint items and select “is less than” and in the far right box select “enrolledDateTime”:

What I’m doing is comparing the single item created date pulled from SharePoint to the enrollment dates pulled from Intune:

SharePoint item created date

Device enrollment dates

  • In the “If Yes” box, add an action, then search and add “Send an email (V2)”. Then select from the dynamic items to craft a mail. We don’t need anything for “If no”.

The next three steps in the Flow are fairly self-explanatory so I expanded them for reference:

What’s occurring  in the “Apply to each 2” is a SharePoint value is selected from the SharePoint Get items step, then I delete the item. Next step is up to you, all I’m doing is converting the current date/time then adding it to the Title field of a new SharePoint list item, however you can do what you want in the middle step, just make sure the last step creates a single SharePoint list item as the created date needs to be referenced in a previous step in this Flow.

Testing the Flow

Once the steps above are complete, run a test to create an item in SharePoint, then register a device and make sure it shows up in Intune under device, then run another test.  So you’ll run two tests, one to generate the SharePoint item, and other after the device is registered with Intune.

The following is the email Power Automate sends to the end user who enrolled the device:

When you’re ready to move this process into production, delete the manual trigger in the first step and replace it with the Recurrence trigger and run it on the interval that is best for your organization:

That’s it, we fully automated a process by using Power Automate to pull all enrolled device objects from Microsoft Intune, selecting only devices that have a UPN associated, and sending an email to end users who have enrolled their devices since the last time the Flow ran.