Microsoft Entra ID App Registration Certs / Client Secret HTML Report

In this post we will be going through creating a HTML report for Microsoft Entra ID App registration to export a list of expired and expiring client secrets and certificates.

I wanted to create a HTML report that would highlight cert / secrets that where expired or due to expire and make it quicker to check what is due to expire.

This report will use the existing PowerShell script I created last year to export Azure App registration details to a CSV file, just updated to use an embedded CSS style sheet to format the html output.

First I needed to create a HTML style sheet, below is the HTML code I use for the HMTL formatting.

The last step was update the rows to set each row to green, orange or red depending on the status of the cert / secret.

To run the script I will be using a certificate and app registration as this allow for better automation and certificate are recommend over client secrets for security. If you need to know how to set this up I have done a previous post on this.

.\Get-AppRegistrationdetailsHTMLv2.ps1 -CertificateThumbprint thumbprint -ClientId ClientID -TenantId TenantID -ReportExport C:\temp\Graph\ -ExpiryDate 200

Below is an example of the full export.

The table and colors can be modified just have to update the style sheet.

To download the full script use the below GitHub link.

https://github.com/TheSleepyAdmin/Scripts/blob/master/MSGraph/AppRegistration/Get-AppRegistrationdetailsHTMLv2.ps1

Azure Service Principals Report Using Microsoft Graph SDK

If you’re an Azure administrator, you’re likely familiar with the concept of service principals.

These are application identities that are used to manage access to Azure resources. Service principals are an important part of Azure security, but managing them can be a challenge.

In this blog post, we’ll go through listing service principals and exporting details and group membership.

First we need to connect to Azure using Microsoft GraphSDK, the two permission required are Group.Read.All and Application.Read.All

Next we can use to list all service principal

Get-MgServicePrincipal -All: $true

We can use the Filter parameter to select only the principal that we want to check.

Next I wanted to check what groups the principal was a member off. To do this we can use the ID property and the below command.

Get-MgServicePrincipalTransitiveMemberOf -ServicePrincipalId

We can then use the ID to get the group display name

Get-MgGroup -GroupId

Now that we have the service principal and groups we can create the report script. We will be exporting the Displayname, ServicePrincipaltype, AccountEnabled, AppId, createddatetime and groups.

There are three parameters in the script, ServicePrincipals is used to specify the name or names of the service principals to check.

The ConsoleOnly returns results directly to PowerShell console

If using the reportexport parameter the results will be exported to CSV

The script can be run against one or multiple service principals to report on more than one.

To search more than one use , between the names.

The full script can be downloaded from the below GitHub link.

https://github.com/TheSleepyAdmin/Scripts/blob/master/MSGraph/ServicePrincipal/Get-ServicePrincipalReport.ps1

Replacing Azure AD and MSOL with Graph PowerShell Module

Support for both Azure AD and MSOL modules have been extended to allow the updating of scripts and I would presume due to some command not existing in Graph yet. The modules will be deprecated in June 30th 2023 so any scripts using command with either of these modules should be updated as soon as possible.

https://learn.microsoft.com/en-us/azure/active-directory/fundamentals/whats-deprecated-azure-ad#upcoming-changes

In this post we will be going through some common commands that use either the Azure AD or MSOL PowerShell modules and how to find commands that will replace them in Graph and using the scope roles to set required API permissions.

First stop I usually do is to check if the commands have direct replacements, we can use the below learn page to check. The page will have tables with the Azure AD / MSOL command and then the replacement command if one exist in the second row.

https://learn.microsoft.com/en-us/powershell/microsoftgraph/azuread-msoline-cmdlet-map?view=graph-powershell-1.0

For the below reference we will be using Get-MsolUser if we check the document that command is replaced by Get-MgUser.

Now when connecting to Azure AD or MSOL all commands and permission are based on the role of the account you sign-in with.

If we connect with MSOL we can query users once we have the required role.

For Graph the way to connect is slightly different if we don’t specify a scope when connecting, we can connect but we don’t automatically have the require API permission assigned so if we run the Get-MgUser command we will get an error for insufficient privilege’s

If we add the -scope User.Read.All

If we want to check what permission are available for a command we can use Find-MgGraphCommand with the command we want to check. We can also use the apiversioni (v1.0 or beta)

Find-MgGraphCommand -Command Get-MgUser -ApiVersion v1.0 |fl

To just return the permission we can use parenthesis to select just the permissions.

(Find-MgGraphCommand -Command Get-MgUser -ApiVersion v1.0).Permissions

Depending on what task we are trying to do we can select the required permission, one example is if I just want to get back information on account’s I would just use User.Read.All. If I wanted to change a users settings I would use the User.ReadWirte.All.

Another difference between modules is that in Graph there is no -userprinicpalname parameter and uses UserID instead

To get licenses assigned to a user we can use.

Get-MgUserLicenseDetail -UserId UPN

As we can see Microsoft Graph has a few differences and instead of having most data under single objects like Get-MsolUser we have to now use multiple commands to return the same data which can be a bit more difficult when starting out.

Microsoft Graph: Restrict Access Using Conditional Access Policy

In this post we will be going through setting up a conditional access policy to allow connection’s to a Microsoft App Registration that will be used for calling Microsoft GraphAPI from only certain countries / public IP’s.

Microsoft has a preview feature in Conditional Access for workload identities. A workload identity is an identity which allows an application or service principal access to resources.

When an App Registration is created, it will create a service principal. This service principal is what we will use in the conditional access policy.

First we need to create the named location to define where we want to allow the access from.

To create a named location go to endpoint management admin page.

https://endpoint.microsoft.com/

Go to Endpoint security > Conditional access.

MEM Admin Page

Once in Conditional access, go to Named location and add the required countries locations and or IP ranges.

Named locations

To add as single IP use /32 bit subnet mask.

IP range

Once we have the named locations we can create the Conditional access policy.

Go to the policies tab and click on new policy.

Policies page

Give the policy a name and set the assignment to workload identities.

Conditional access policy

Next select the service principal for the Graph App registration.

Users or workload selection

Next on Cloud apps or actions select, All cloud apps

Cloud apps or actions selection

Next we need to specify which location will be included, which we set to any location as we will use the exclude to allow access from the named location we will connect from.

Conditions selection

Next select the location that will be excluded from the policy in my case it will be the public IP we added earlier to the named location.

Excluded Locations

Next we set the access, I will be blocking access as I only want to allow access from the one public IP we specified in the excluded location.

Access selection

With any conditional access policy I would recommend setting the policy to Report-only to confirm that only the access that we excepted to be blocked is.

Policy settings enabled section

To check if the policy is applying correctly against the service principal we can check the sign-in logs.

First connect using Graph query and then go to sign-in logs.

MEM Admin Blade

Select service principal sign-ins.

Sign-in logs

Click on the request ID and look at the Report-only tab to see if the access would have been blocked or allowed.

Sign-in logs

Once we confirm that the policy is applying the correct access, the conditional access can be set to on.

Now once we try to connect from an IP or location not on the excluded list, it will be blocked from accessing.

Graph Connection

When we connect from an allowed location, we will get back the access token and be allowed to connect.

Graph Connection Token

When creating App registration we should look at access controls for these as this can be over looked and lead to a security risk, most application do not need access from any location and should be limited to only the require location or IP address to give greater access control.

Microsoft Graph: Restrict Exchange Online Mailbox Access

Recently we have been reviewing some of our old Exchange Web Service mailbox connections and updating these to use Microsoft Graph. We wanted to restrict what mailbox’s the Azure App registration used for Microsoft Graph could connect to.

To set this up in Exchange Online we can use an Application Access Policy. In this post we will be going through setting up and confirming the mailbox’s access.

I have gone through setting up Azure App registration for Microsoft Graph before so we wont be going through that in this post.

I will also be using certificate and Microsoft MSAL PowerShell Module to get the Graph access token.

See post below if you need to know how to connect using MSAL with certificate base authentication.

Once we have the app registration setup and certificate issued and uploaded to the app registration, we can then assign the GaphApi permission to access mailboxes.

If we don’t apply the permission we will get access denied.

Graph Message Access Error

I will be giving Mail.Read API permission, this will give access to view all mailboxes.

Graph API Permissions

Grant admin consent for the API permission.

Now if we try to query the mailbox we should now be able to see the messages.

Graph Message Response

At this stage we can use the App registration to read messages from any mailboxes.

To lock this down so that the Graph query is only able to view certain mailboxes we can use

New-ApplicationAccessPolicy

to create an application access policy. The policy can be applied to a group or a single users.

To run the command, we will need Application ID of the app registration, mailbox or mail enabled security group and description. Using a group is useful if there are multiple mailboxes that they will need to allow access.

New-ApplicationAccessPolicy -AppId ApplicationID -PolicyScopeGroupId "user_group@domain.com" -AccessRight RestrictAccess -Description "Restrict this app to view mailbox or security group."

To run the command we need to connect to Exchange Online

Connect-ExchangeOnline

Then run the command to create the application access policy.

We can test what mailboxes the app registration can access using.

Test-ApplicationAccessPolicy -AppId ApplicationID -Identity user_group@domain.local

Now once we try to query the mailbox we have give access to we will see the message returned, if we try query any other mailbox we will an error message.

Applying the application access policy is a good idea for security as allowing an application to read mailboxes that it doesn’t need access to can be a risk if the app was ever compromised or there is sensitive data in mailboxes that no other users or application should have access to.

Azure App Registrations Cert / Client Secret MS Graph Report

In this post we will be looking at creating a report to show what Azure App registrations have expiring client secret / certificate in the specified amount of days.

There is currently no in built way to report on expiring App registrations in the Azure portal other than checking the app registration, so we will be using Microsoft Graph SDK to automate the reporting.

First to automate the report we need to create an app registration to use for the Microsoft Graph connection. I have gone through this in a previous post.

The specific Microsoft GraphApi application permission required is Application.Read.All, this needs to be added to the App Registration that we use for Microsoft Graph.

App Registration API Permission

Next we need to connect to Microsoft Graph using.

Connect-MgGraph

To list the app registration use

Get-MgApplication
Microsoft Graph Applications

Once we have the list of apps we can use PasswordCredentials to view client secret details

(Get-MgApplication).PasswordCredentials
Application Secrets Properties

and KeyCredentials to view the certificates details

Application Certificate Properties

Once we have the required properties, we can create the script to export the app registration details.

App Registration Report

There are two parameters Reportonly which returns just the result to PowerShell window and ReportExport which will export the report to the specific folder specified.

Below is what the Reportonly should look like.

.\Get-AppRegistrationDetails.ps1 -CertificateThumbprint Thumprint -ClientId ClientID -TenantId TenantID -ReportOnly -ExpiryDate 200
Report results

When using the Reportexport

.\Get-AppRegistrationDetails.ps1 -CertificateThumbprint thumbprint -ClientId ClientID -TenantId TenantID -ReportExport C:\temp\Graph\ -ExpiryDate 200

The full script can be downloaded from the below GitHub link.

https://github.com/TheSleepyAdmin/Scripts/blob/master/MSGraph/AppRegistration/Get-AppRegistrationDetails.ps1

Microsoft Graph Report on Azure Role Assignments

In this post we will be going through creating an automate report to list all assigned Azure roles and user/group assignments using Microsoft Graph SDK.

This can be useful for environments that haven’t implemented Microsoft privileged identity management for roles management. This can be used to keep track of roles assignments in Azure.

I will be using Microsoft Graph SDK, if you haven’t used this before I have done a previous post on installing and getting start with the Graph SDK.

I will be using a app registration in Azure AD with certificate authentication (I covered this in one of my previous posts) so I don’t have to use any username or password with the script. We will need to add the required API permission.

To find the specific commands that I needed to use, I generally search for them on the Graph module reference document link below as there are a lot of commands in the Graph SDK module.

https://docs.microsoft.com/en-us/powershell/module/microsoft.graph.applications/?view=graph-powershell-beta

To add the API permission logon to Azure portal

https://portal.azure.com

Open Azure Active Directory > App registrations

Select the Graph registration that was previously created. Under the API permissions select add permissions and add the the required application permissions to run the command.

In this case we will be using the rolemanagment.read.all

Once the API permission is added we can start to create the script.

To get the list of directory roles that are currently in use use

Get-MgDirectoryRole

Then to get the assigned objects use the below command and copy the ID to view details.

Get-MgDirectoryRoleMember -DirectoryRoleId IDValue

To view addtional values for the returned object use

(Get-MgDirectoryRoleMember -DirectoryRoleId IDValue).AdditionalProperties

The full script can be downloaded from the below github link and

https://github.com/TheSleepyAdmin/Scripts/blob/master/MSGraph/RoleAssigment/Get-AdminRolesAssigment.ps1

Below is what the export will look like.

Microsoft Graph Filtering Results PowerShell

During a recent audit we have been trying to automate a report on what Guest account’s are active in the last 30 days and to find what groups these guest account are members of so they can be removed if they are no longer required.

We could use AzureAD PowerShell for getting guest account and group membership but it was not that easy to automate this.

We decided to use Microsoft Graph as we have a few task already automated using Microsoft Graph and certificates so there is no need to hard code any password or application secret in my script.

I have done a previous post on the getting the access token and using certificate based authentication so if you need to know how to setup you can check that post.

Connect to Microsoft Graph using MSAL and Certificate based Authentication – TheSleepyAdmins

In this query we will be using three different Microsoft Graph url’s. First is to get a list of guest users, second will be to get sign-in logs and the last will be to get the guest users group membership.

To get guest users we will filtering using userType attribute

user resource type – Microsoft Graph v1.0 | Microsoft Docs

below are the permission that will be required

ApplicationUser.Read.All, User.ReadWrite.All, Directory.Read.All, Directory.ReadWrite.All

To get sign-in’s we will be filtering on two different attributes (userPrincipalName & createdDateTime)

List signIns – Microsoft Graph v1.0 | Microsoft Docs

below are the permission that will be required

ApplicationAuditLog.Read.All and Directory.Read.All

To get Group membership we will be using the memberof

user: getMemberGroups – Microsoft Graph v1.0 | Microsoft Docs

below are the permission that will be required for getting the group membership.

ApplicationUser.Read.All, Directory.Read.All, Directory.ReadWrite.All

First step as with any Graph query is to create the token request that will be used to access the different Graph Url’s. We will be using MSAL module and a certificate to generate.

To filer results using Graph we can put in ?filter= and then use a supported filter attribute. In this case we will be using usertype.

We will also create a blank array variable that will be used to output to later and a date variable to filer the sign-in logs.

This first filter will get all guest users. Currently usertype is only available when using the beta Graph version so we will be using that.

"https://graph.microsoft.com/beta/users/?filter=usertype eq 'Guest'"

Once we have the Guest users we will loop through each one, use a second filter that uses the mail address to filter the guest user sign-in logs and use a date variable to show only sign-in over the last 30 days.

"https://graph.microsoft.com/beta/auditLogs/signIns/?filter=userPrincipalName eq '$($User.mail)' and createdDateTime ge $Date"

The next filter is going to use the user ID to get the memberof for the user and we will use the group-object to put all groups display names in to one object so it easier to call to the console windows or export to a CSV.

"https://graph.microsoft.com/beta/users/$($User.ID)/memberof"

Once we have all the information returned from the Graph queries we need to format the results. For this we will use a hash table and an if statement to output user with or without sign-in logs to the correct hash table and add the values to the results variable.

This script is only going to return the latest sign-in log as I only really want to have a report that the users has been active in the last 30 day that’s why I am using [0] to select the latest object in the $logins variable.

The last part of the script just outputs the results and use select-object to format the order.

Now that we have the full script the below is what the result should look like.

To make the script more reusable there are three variable for TenantId , ClientId and CertThumprint.

To export the result to a csv instead of the console windows there is an -Exportpath parameter that just needs to have the path specified.

The full script can be download from my Github repository

Scripts/MSGraph/GuestUserAuditReport at master · TheSleepyAdmin/Scripts (github.com)

To filter on other attributes we can use the same process as above just change the Graph url and check the document for that url to view what is a valid filter attribute. Filtering results in the the Graph url speeds up the script and mean we don’t do addtional filtering after returning all data.

Connect to Microsoft Graph using MSAL and Certificate based Authentication

I had a recently gotten some question’s on how to connect to Microsoft GraphApi using certificate instead of an app secret. I have set this up before using the Microsoft Graph PowerShell SDK but I wanted to test this using Invoke-RestMethod.

There is a PowerShell module that has been created that allow for much easier creation of authentication tokens using Microsoft Authentication Library.

Learn about MSAL – Microsoft identity platform | Microsoft Docs

The Microsoft Authentication Library (MSAL) enables developers to acquire tokens from the Microsoft identity platform in order to authenticate users and access secured web APIs. It can be used to provide secure access to Microsoft Graph, other Microsoft APIs, third-party web APIs, or your own web API. MSAL supports many different application architectures and platforms including .NET, JavaScript, Java, Python, Android, and iOS.

MSAL gives you many ways to get tokens, with a consistent API for a number of platforms. Using MSAL provides the following benefits:

  • No need to directly use the OAuth libraries or code against the protocol in your application.
  • Acquires tokens on behalf of a user or on behalf of an application (when applicable to the platform).
  • Maintains a token cache and refreshes tokens for you when they are close to expire. You don’t need to handle token expiration on your own.
  • Helps you specify which audience you want your application to sign in (your org, several orgs, work, and school and Microsoft personal accounts, social identities with Azure AD B2C, users in sovereign, and national clouds).
  • Helps you set up your application from configuration files.
  • Helps you troubleshoot your app by exposing actionable exceptions, logging, and telemetry.

The PowerShell module that can be used to create tokens is called MSAL.PS and the latest version as of today is 4.21.0.1.

PowerShell Gallery | MSAL.PS 4.21.0.1

In this post we will be going through installing and using this module to generate an authentication token using a self signed certificate and using that token to connect to Microsoft Gaph.

The first step is to install the MSAL.PS module

Once the module is installed we can generate the certificate that will be used to connect to Microsoft Graph

To create the self signed cert I used the below command. There was a error when trying to generated the token when I didn’t use -KeySpec when generating the cert. The fix to use -KeySpec was on the GitHub issue page.

Get-MsalToken with Client Certificate fails on Windows PowerShell 5.1 · Issue #15 · AzureAD/MSAL.PS (github.com)

New-SelfSignedCertificate -DnsName TennatDomainName -CertStoreLocation "Cert:\CurrentUser\My" -FriendlyName "MSAL_Cert" -KeySpec Signature

Once the cert has been created, export the cert so that it can be uploaded to the App registration.

Get-ChildItem Cert:\CurrentUser\my\CertThumbprint | Export-Certificate -FilePath C:\temp\Graph_MSAL_Cert.cer

Once the cert is exported we can upload to the app registration that we created before. See previous post if app registration hasn’t been created in Azure yet for Microsoft Graph.

Connecting to Microsoft GraphAPI Using PowerShell – TheSleepyAdmins

To add the cert open the Azure portal > Azure Active Directory >  App registrations and select the Graph app and go to certificates & secrets

Select upload certificate

Click add to apply the cert

After the cert is upload we should now be able to connect. We will need the TenantId, clientId and certificate

The tenantID and ClientId can be gotten from the app registration overview page and the cert can be gotten using Get-Item and the cert location / thumbprint.

Import-Module MSAL.PS
$TenantId = "TenantId"
$ClientId = "ClientId" 
$ClientCert = Get-ChildItem "Cert:\CurrentUser\my\CertThumbprint"
$MSToken = Get-MsalToken -ClientId $ClientId -TenantId $TenantId -ClientCertificate $ClientCert

If you want to use the same cert for any users on the device we can export and import the cert under localmachine cert store with the private key and update the $clientCert to use localmachine instead of currentuser.

Get-Item "Cert:\localmachine\my\CertThumbprint"

Once we have the token, it’s now the same process as we have used before to connect using invoke-restmethod but using the $MSToken.AccessToken we generated using the Get-MsalToken and our certificate.

$GraphGroupUrl = 'https://graph.microsoft.com/v1.0/Groups/'
(Invoke-RestMethod -Headers @{Authorization = "Bearer $($MSToken.AccessToken)"} -Uri $GraphGroupUrl -Method Get).value.displayName

Using MSAL.PS module provides a much quicker and easier way to generate access tokens for Microsoft Graph with the added security of using a certificate over having to put in any application secret.

Microsoft Graph API Result Size Limit

Recently we have been running some Microsoft Graph API queries and were not getting back all the results expected.

Microsoft Graph seems to have a limit of 1000 results for signin logs, when the limit is reached graph will then start paging the result and adding them to @odata.nextLink property.

There is a Microsoft doc on paging in Graph.

Paging Microsoft Graph data in your app – Microsoft Graph | Microsoft Docs

There are different limits depending on the API.

Below is an extract from the paging doc.

Paging behavior varies across different Microsoft Graph APIs. Consider the following when working with paged data:

  • Different APIs might have different default and maximum page sizes.
  • Different APIs might behave differently if you specify a page size (via the $top query parameter) that exceeds the maximum page size for that API. Depending on the API, the requested page size might be ignored, it might default to the maximum page size for that API, or Microsoft Graph might return an error.
  • Not all resources or relationships support paging. For example, queries against directoryRoles do not support paging. This includes reading role objects themselves as well as role members.

The @odata.nextLink then needs to be called to get the addtional results.

When we run a query and the results are under the limit there will be two objects returned

@odata.context and value

If we run a query that goes over the max results limit of 1000 the value object is changed to @odata.nextLink

If we use count on the $Results variable it returns 996 items.

To query the addtional results we need to loop through each page to extract the results.

To loop through the results we can create a new variable with the @odata.nextLink and use while loop to go through the variable to get results from the pages.

When we do this the $results count go up to 1142

Below is the full script to get the addtional results.

$ApplicationID = ""
$TenatDomainName = ""
$AccessSecret = Read-Host "Enter Secret"


$Body = @{    
Grant_Type    = "client_credentials"
Scope         = "https://graph.microsoft.com/.default"
client_Id     = $ApplicationID
Client_Secret = $AccessSecret
} 

$ConnectGraph = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$TenatDomainName/oauth2/v2.0/token" `
-Method POST -Body $Body

$token = $ConnectGraph.access_token

$LoginUrl = "https://graph.microsoft.com/v1.0/auditLogs/signIns"
$LoginResults = Invoke-RestMethod -Headers @{Authorization = "Bearer $($Token)" } -Uri $LoginUrl -Method Get

$Results = @()
$Results += $LoginResults.value

$Pages = $LoginResults.'@odata.nextLink'
while($null -ne $Pages) {

Write-Warning "Checking Next page"
$Addtional = Invoke-RestMethod -Headers @{Authorization = "Bearer $($Token)" } -Uri $Pages -Method Get

if ($Pages){
$Pages = $Addtional."@odata.nextLink"
}
$Results += $Addtional.value
}

If using the Microsoft Graph SDK the process is much simpler.

Once connect to using Connect-Mgraph we can then run

Get-MgAuditLogSignIn | 
Select-Object UserDisplayName,UserPrincipalName,IPAddress,AppDisplayName,ResourceDisplayName,ClientAppUsed,CreatedDateTime

The $signins results variable returns the same 996 results as we got with the above invoke-restmethod graph api query.

To get all the addtional results all we need to do is add the -All parameter and this should then return all results.

This shows the two different method to get the larger results from GraphAPI queries.