Generate Azure AD Temporary Access Pass using PowerShell and MS Graph API

Generate AAD TAP using PowerShell and MS Graph API

In my previous blog on Azure AD Temporary Access Pass (AAD-TAP) currently available in preview, I talked about the new authentication method made available and also showed how you can generate TAP for users using the Azure AD portal.

However, the Azure AD portal only allows you to generate Temporary Access Pass for users one at a time. As such in this blog post, I will show you how you can easily make use of the Microsoft Graph API via PowerShell to generate Azure AD Temporary Access Pass for multiple users at the same time.

Let’s get started.

Easily figure out URI to make MS Graph API calls

If you are new to Microsoft Graph and unsure of how to construct the URI for the purpose of making Graph API calls, you can always use the portal as your reference. Anything that we do on the portal actually takes effect with help of a backend Graph API call.

As such, when you perform any administrative task on the portal, before you commit the action

  • press F12 to bring up the browser console,
  • ensure traffic monitoring is on,
  • check for the network activities that will get logged post you commit,

and you would be able to see the Graph API call being made for the action your performed on the portal.

Easily figure out URI to make MS Graph API calls - Every action on the portal is enacted by a backend Graph API call being made.
Easily figure out URI to make MS Graph API calls – Every action on the portal is enacted by a backend Graph API call being made.

Using the same method, from the above snap, we can see the Graph API call made to generate AAD TAP for a user to make out the URI that we need to construct the Graph API call from PowerShell. The URI format is as shown

https://graph.microsoft.com/beta/users/{userGUID_or_userUPN}/authentication/temporaryAccessPassMethods

[Test] Generate Azure AD Temporary Access Pass using Graph Explorer

Ensure you have the correct permissions consented for in Graph Explorer.

The Graph API documentation for Azure AD Temporary Access Pass mentions that to access the particular resource and work with it, the caller requires to have Admin consent provided for the permission UserAuthenticationMethod.ReadWrite.All

You can generate Temporary Access Pass for a user by sending a POST query to the Microsoft Graph, using the above URI structure as reference.

Now we know that a POST/PUT/PATCH call requires to provide a JSON body as the query payload.

Check Graph API documentation for the resouce type to create the JSON body to construct the Graph API POST call.
Check Graph API documentation for the resouce type to create the JSON body to construct the Graph API POST call.

However checking Graph documentation for Temporary Access Pass, you will see that it does not actually requires you to supply values for any Parameters in the Request body since none of the Parameters are marked as Required.

Thus running the POST query with an empty Request body suffices to generate TAP for the user successfully using Graph Explorer.

Generate Azure AD Temporary Access Pass using Graph Explorer
Generate Azure AD Temporary Access Pass using Graph Explorer

Keep in mind that you would still need to define an empty Request body { }, otherwise you would expect this error.

Empty payload for MS Graph API POST cal results in error.
Empty payload for MS Graph API POST cal results in error.

Also, note that the value of the Temporary Access Pass is shown only in the response to the POST call. As such, like in the case of using the GUI portal, if you do not take a note of the same, you can’t retrieve it using a GET call later as shown below.

Value of Temporary Access Pass is only returned as response to the API POST call and can't be retrieved later using a API GET call.
Value of Temporary Access Pass is only returned as response to the API POST call and can’t be retrieved later using a API GET call.

If you want, you can define the parameters in the Request body as shown below

Request headers

Content-Type: application/json
Content-length: 209

Request body 

{
  "@odata.type": "#microsoft.graph.temporaryAccessPassAuthenticationMethod",
  "startDateTime": "yyyy-mm-dd hh:mm:ss",
  "lifetimeInMinutes": "mm",
  "isUsableOnce": "true/false"
}

Now that we have seen how to use Microsoft Graph API to generate Azure AD TAP using Graph Explorer, lets also see how we can do the same using PowerShell.

[Final] Generate Azure AD Temporary Access Pass using PowerShell and MS Graph API

Pre-requisites

  • The post assumes that you have an application registered in Azure with the required permissions consented to the application.
  • Further, the user account you will use to authenticate during script run should have Application Administrator/Cloud Application Administrator role assigned. If not, the consent to permission flow will require approval from an Admin having the roles mentioned.
Are you aware of my recent blog series Learn How to Use Microsoft Graph API with Joy? If not, here are the links to the posts that can help you get started with Microsoft Graph API and making API calls from PowerShell.

Post #1 - Explore Graph with Graph Explorer - Getting started with MS Graph API
Post #2 - Understanding AUTH for MS Graph API
Post #3 - Get started with PowerShell to run Graph API queries - Part 1
Post #4 - Get started with PowerShell to run Graph API queries - Part 2

Choice of Auth flow and Permission type to generate Azure AD Temporary Access Pass

Microsoft Graph documentation for Temporary Access Pass shows that it supports both Delegated and Application permission types for the purpose.

Generate Azure AD Temporary Access Pass using PowerShell and MS Graph API - Check Graph API documentation for required Permissions.
Generate Azure AD Temporary Access Pass using PowerShell and MS Graph API – Check Graph API documentation for required Permissions.

However, as per security best practice, I would advise sticking with Delegated permission instead of Application permission. This ensures only an Admin user having the required roles would be able to generate AAD TAP for other users.

Below are all the permissions that you would require to add to your application registered in Azure AD and have the same consented by an Admin so that you can connect to and work with MS Graph for generating Temporary Access Pass for your users using the PowerShell script.

Permission TypePermission
DelegatedUser.Read
DelegatedUser.Read.All
DelegatedUser.ReadBasic.All
DelegatedDirectory.Read.All
DelegatedUserAuthenticationMethod.ReadWrite.All

Once the permissions are added to the application in Azure and consented to, you can start working on your script.

Obtain Access Token to work with MS GRAPH

First we would need to take care of authenticating and getting an access token from the Microsoft Identity service.

Since here we are dealing with Delegated permission type, we require to use an Auth flow method that involves interactive user sign-in. I will be using the MSAL.PS module function Get-MsalToken for this purpose again.

<# Region Auth Start #>
$tenantId = "<Your Tenant ID Here>"
$clientID = "<Your registered Application ID here>"
$Scope = "https://graph.microsoft.com/.default"
$redirectUri = "https://localhost"
$TokenResponse = Get-MsalToken -ClientId $clientID -TenantId $tenantId -Interactive -RedirectUri $redirectUri -Scopes $Scope
<# Region Auth End #>

Running the above code will prompt you for an interactive sign-In, where post providing your credentials, you will be asked to provide consent to using the permissions.

Generate Azure AD Temporary Access Pass using PowerShell and MS Graph API - Consent to the Permissions requested.
Generate Azure AD Temporary Access Pass using PowerShell and MS Graph API – Consent to the Permissions requested.

The permissions you see here are what has been assigned to the application in Azure since we are using the static scope ./default. The Access Token obtained post successful AUTH remains stored in the variable $TokenResponse.

Generate Azure AD Temporary Access Pass using PowerShell and MS Graph API - Viewing obtained Access Token.
Generate Azure AD Temporary Access Pass using PowerShell and MS Graph API – Viewing obtained Access Token.

Now that we have authenticated to Graph and have the access token, we can go ahead and build our Graph API query to  generate Azure AD Temporary Access Pass for a bulk of Users utilizing the scripting functionalities of PowerShell.

Generate Azure AD Temporary Access Pass at bulk using PowerShell utilizing the Graph API

<# Region Generate AAD TAP Start #>

#Import users from csv file
###########################
$users = (Import-csv -Path "c:\Temp\users.csv").UserName

#Initializing Hash table to store output
########################################
$hash = @{} 

#Looping through each user to generate AAD TAP
##############################################

ForEach ($user in $users) {
	$Headers = @{Authorization = "$($TokenResponse.token_type) $($TokenResponse.access_token)"}
	$tapUri = "https://graph.microsoft.com/beta/users/$user/authentication/temporaryAccessPassMethods"
	$body = "{}"
	$tapResponse = Invoke-RestMethod -Headers $Headers -Uri $tapUri -Body $body -Method POST -ContentType "application/json"
	$tap = $tapResponse.temporaryAccessPass
	$hash.add($user,$tap)
}

#Saving result to file
######################

$outpath = "C:\Temp\Results.csv"
$hash.GetEnumerator() | Select-Object -Property @{N='User Name';E={$_.Key}}, @{N='Temporary Access Pass';E={$_.Value}} |Export-csv -Path $outpath -NoTypeInformation

<# Region Generate AAD TAP End #>

As you would have noticed, I have used a Hash Table to store the User and its associated generated Temporary Access Pass on each iteration of the loop. The Hash Table is itself stored in the variable $hash, which I am then exporting to a CSV with a little bit of structuring.

Generate Azure AD Temporary Access Pass using PowerShell and MS Graph API
Generate Azure AD Temporary Access Pass using PowerShell and MS Graph API

The above snap shows what the variable contains after running the script, which I am then saving to a CSV file. This is how the generated CSV looks like.

Save the generated Azure AD TAP for the Users to a CSV file.
Save the generated Azure AD TAP for the Users to a CSV file.

The End

This is just an example to show how you can use Microsoft Graph API and PowerShell to achieve automation of bulk actions or complex workflows easily, which otherwise would have required more manual effort if done via the portal.

By combining the scripting prowess of PowerShell with the flexibility and usability of Microsoft Graph API, you can do wonders in automating workloads in your M365 environment.

That’s all for today. Hope you would find this post informative and useful.