Avoid the Oops: Proactively Monitor Entra Application Secret Expirations with Automation

In the fast-paced world of enterprise IT, even small oversights can lead to major disruptions. One of those easily overlooked — yet critically important — tasks is monitoring Microsoft Entra (formerly Azure AD) application secret expirations.

Imagine this: everything is running smoothly in production until — bam! — an app suddenly fails because its secret expired. No alerts, no heads-up, just user complaints and a flurry of incident reports. Sound familiar?

Why Monitoring Application Secrets Matters

At its core, application secrets are credentials that apps use to authenticate themselves with Microsoft Entra ID. But unlike passwords, secrets come with an expiration date. If they aren’t renewed in time, the app’s authentication fails — and with it, the business processes it supports.

For organizations running dozens (or hundreds) of app registrations, staying ahead of these expirations is not optional — it’s essential. Secrets that silently expire can grind systems to a halt, disrupt integrations, and worst of all, trigger security incidents or SLA breaches.

A Common Problem in the Real World

When I first set out to automate monitoring for app secret expirations, I assumed it’d be simple. A few PowerShell lines here, an API call there, maybe some Logic App magic… problem solved, right?

Well, not quite.

Most of the tutorials and blog posts I found focused solely on fetching the expiration date of secrets — they showed how to query the data, but not how to operationalize it. I wanted something that would proactively notify the right people before things went south.

Eventually, I came across a helpful post on Microsoft Tech Community:
Use Azure Logic Apps to Notify of Pending AAD Application Client Secrets and Certificate Expirations

It was a solid foundation. The Logic App would periodically check secrets and send an email notification if one was nearing expiration.

But then… I hit a snag.

If an application had multiple owners — which, in the enterprise world, is very common — the Logic App would only notify the first listed owner. Everyone else? Left in the dark.

Not ideal. Especially when that one person is on PTO, has left the company, or, let’s be honest, just ignores emails from IT.

So, I decided to roll up my sleeves and build a PowerShell-based solution that:

  • Queries all app registrations
  • Checks for secrets or certificates nearing expiration
  • Looks up all owners (not just the first one)
  • Sends clear, actionable email notifications to each owner

Why Automate This? Let’s Talk Benefits

Here’s why every enterprise IT team should care about automating secret expiration alerts:

  • Proactive Security – Timely notifications help you spot secrets that are about to expire — before they become a security risk or business disruption. It’s the difference between being reactive and being prepared.
  • Reduced Downtime – Missed secret expirations lead to failed authentications, which means broken apps. Proactive alerts buy you time to renew secrets and avoid outages.
  • No More Manual Tracking – Maintaining a spreadsheet of app secrets? Been there. Done that. Automation means less grunt work and fewer mistakes.
  • Smart Notifications – By targeting all app owners — not just the first in line — you’re covering your bases. Even if someone’s on vacation, someone else sees the alert and can take action.

What This Script Does

  • Authenticates to Microsoft Graph with the required permissions
  • Queries all Entra app registrations
  • Identifies app secrets and certificates that are expiring within a defined threshold (e.g., 30 days)
  • Pulls all assigned owners for each app
  • Sends an email notification to each owner with details about the impending expiration
  • Sends an email notification to an administrator email, a distribution group or a shared mailbox containing a list of all secrets that are expiring

Use task scheduler to run this script from your on-premise environment. You can securely store the credentials to be used in the PowerShell script using the SecretManagement module. I’ve covered this in detail in an earlier post here. The ideal and preferred method is to use Azure automation account which is much more easier and secure, which I will cover in a future post.

# Connect to Microsoft Graph
Connect-MgGraph -Scopes "Application.Read.All","User.Read.All","AppRoleAssignment.Read.All"

# Set default value for the number of days until expiration
$DaysUntilExpiration = 30

# Email configuration
$SmtpServer = "smtp.yourdomain.com"
$From = "alerts@yourdomain.com"
$DefaultEmail = "entra_app_cert_notif@yourdomain.com"

# Function to send email
function Send-ExpirationAlert {
    param (
        [string]$To,
        [string]$FirstName,
        [string]$AppName,
        [string]$SecretOrCertName,
        [string]$SecretOrCertId,
        [datetime]$EndDate
    )

    $Subject = "Alert: Secret or Certificate Expiration Notice for $AppName"
    $Body = @"
<html>
<body>
<p>Hello $FirstName,</p>
<p>This is a notification that the secret or certificate named '$SecretOrCertName' for the application '$AppName' will expire on $($EndDate.ToShortDateString()).</p>
<p>Please contact Progressrail's Entra (previously known as Azure AD) Administrators and take the necessary actions to renew or replace the secret or certificate before it expires.</p>
<p>Details to provide the administrators:</p>
<ul>
<li>Application Name: $AppName</li>
<li>Secret or Certificate Name: $SecretOrCertName</li>
<li>Secret or Certificate ID: $SecretOrCertId</li>
<li>Expiration Date: $($EndDate.ToShortDateString())</li>
</ul>
<p><span style="color: red;">Please do not reply to this email, this mailbox is not monitored.</span></p>
<p>Thank you,<br>Your IT Team</p>
</body>
</html>
"@

    Send-MailMessage -SmtpServer $SmtpServer -From $From -To $To -Subject $Subject -Body $Body -BodyAsHtml
}

# Function to send summary email
function Send-SummaryEmail {
    param (
        [string]$To,
        [string]$Body
    )

    $Subject = "Summary: Secrets and Certificates Expiring in the Next 30 Days"
    Send-MailMessage -SmtpServer $SmtpServer -From $From -To $To -Subject $Subject -Body $Body -BodyAsHtml
}

# Get the current date
$Now = Get-Date

# Query all applications
$Applications = Get-MgApplication -All

# Initialize a variable to store the summary of expiring secrets and certificates
$SummaryBody = @"
<html>
<body>
<p>Hello,</p>
<p>The following secrets and certificates are expiring in the next 30 days:</p>
<table border="1">
<tr>
<th>Application Name</th>
<th>Secret or Certificate Name</th>
<th>Secret or Certificate ID</th>
<th>Expiration Date</th>
</tr>
"@

# Process each application
foreach ($App in $Applications) {
    $AppName = $App.DisplayName
    $AppID   = $App.Id
    $ApplID  = $App.AppId

    $AppCreds = Get-MgApplication -ApplicationId $AppID
    $Secrets = $AppCreds.PasswordCredentials
    $Certs   = $AppCreds.KeyCredentials

    foreach ($Secret in $Secrets) {
        $StartDate  = $Secret.StartDateTime
        $EndDate    = $Secret.EndDateTime
        $SecretName = $Secret.DisplayName
        $SecretId   = $Secret.KeyId

        $Owners = Get-MgApplicationOwner -ApplicationId $App.Id

        if ($Owners.Count -eq 0) {
            # No owner information, send to default email
            $FirstName = "Admin"
            Send-ExpirationAlert -To $DefaultEmail -FirstName $FirstName -AppName $AppName -SecretOrCertName $SecretName -SecretOrCertId $SecretId -EndDate $EndDate
        } else {
            foreach ($Owner in $Owners) {
                $Username = $Owner.AdditionalProperties.userPrincipalName
                $OwnerID  = $Owner.Id

                if ($null -eq $Username) {
                    $Username = $Owner.AdditionalProperties.displayName
                    if ($null -eq $Username) {
                        $Username = '**<This is an Application>**'
                    }
                }

                # Extract first name from givenName or user principal name
                $FirstName = $Owner.AdditionalProperties.givenName
                if ($null -eq $FirstName -or $FirstName -eq '') {
                    $FirstName = $Username.Split('@')[0].Split('.')[0]
                }

                $RemainingDaysCount = ($EndDate - $Now).Days

                if ($RemainingDaysCount -le $DaysUntilExpiration -and $RemainingDaysCount -ge 0) {
                    if ($Username -ne '<<No Owner>>') {
                        Send-ExpirationAlert -To $Username -FirstName $FirstName -AppName $AppName -SecretOrCertName $SecretName -SecretOrCertId $SecretId -EndDate $EndDate
                    }
                }
            }
        }

        # Add to summary if expiring in the next 30 days
        if ($RemainingDaysCount -le $DaysUntilExpiration -and $RemainingDaysCount -ge 0) {
            $SummaryBody += @"
<tr>
<td>$AppName</td>
<td>$SecretName</td>
<td>$SecretId</td>
<td>$($EndDate.ToShortDateString())</td>
</tr>
"@
        }
    }

    foreach ($Cert in $Certs) {
        $StartDate  = $Cert.StartDateTime
        $EndDate    = $Cert.EndDateTime
        $CertName   = $Cert.DisplayName
        $CertId     = $Cert.KeyId

        $Owners = Get-MgApplicationOwner -ApplicationId $App.Id

        if ($Owners.Count -eq 0) {
            # No owner information, send to default email
            $FirstName = "Admin"
            Send-ExpirationAlert -To $DefaultEmail -FirstName $FirstName -AppName $AppName -SecretOrCertName $CertName -SecretOrCertId $CertId -EndDate $EndDate
        } else {
            foreach ($Owner in $Owners) {
                $Username = $Owner.AdditionalProperties.userPrincipalName
                $OwnerID  = $Owner.Id

                if ($null -eq $Username) {
                    $Username = $Owner.AdditionalProperties.displayName
                    if ($null -eq $Username) {
                        $Username = '**<This is an Application>**'
                    }
                }

                # Extract first name from givenName or user principal name
                $FirstName = $Owner.AdditionalProperties.givenName
                if ($null -eq $FirstName -or $FirstName -eq '') {
                    $FirstName = $Username.Split('@')[0].Split('.')[0]
                }

                $RemainingDaysCount = ($EndDate - $Now).Days

                if ($RemainingDaysCount -le $DaysUntilExpiration -and $RemainingDaysCount -ge 0) {
                    if ($Username -ne '<<No Owner>>') {
                        Send-ExpirationAlert -To $Username -FirstName $FirstName -AppName $AppName -SecretOrCertName $CertName -SecretOrCertId $CertId -EndDate $EndDate
                    }
                }
            }
        }

        # Add to summary if expiring in the next 30 days
        if ($RemainingDaysCount -le $DaysUntilExpiration -and $RemainingDaysCount -ge 0) {
            $SummaryBody += @"
<tr>
<td>$AppName</td>
<td>$CertName</td>
<td>$CertId</td>
<td>$($EndDate.ToShortDateString())</td>
</tr>
"@
        }
    }
}

# Close the HTML table and body
$SummaryBody += @"
</table>
<p>Thank you,<br>Your IT Team</p>
</body>
</html>
"@

# Send the summary email
Send-SummaryEmail -To $DefaultEmail -Body $SummaryBody

Monitoring Entra application secret expirations may not be the flashiest part of your security strategy, but it’s one of the most crucial. It’s also one of those tasks that’s easy to automate, but costly to ignore.

If you’re currently relying on manual processes — or using a Logic App that only pings one owner — consider leveling up your approach. A bit of PowerShell and planning can save you hours of downtime, reduce late-night incident calls, and help keep your environment secure.

Thank you for stopping by. ✌️

Azure Role-Based Access: Who’s Got the Keys to the Cloud Castle?

Alright, let’s talk about Azure Role-Based Access Control (RBAC)—the bouncer at the club, the gatekeeper of your cloud kingdom, the difference between “Oops, I deleted the production database” and “Phew, good thing I didn’t have permission for that.”

If you’re working with Microsoft Azure, RBAC is a must-know. It’s how you control who can do what in your cloud environment. Let’s break it down in a fun, easy-to-digest way.


What is Azure RBAC, and Why Should You Care?

Think of Azure RBAC like a high-tech office building with keycards. Not everyone should have access to every room, right? Your interns shouldn’t be able to access the CEO’s private office, and the janitor doesn’t need the nuclear launch codes.

RBAC works the same way in Azure:

  • You assign roles to users, groups, or applications instead of just giving them full access.
  • It’s based on the principle of least privilege, meaning people only get access to what they need—nothing more, nothing less.
  • It prevents chaos. Because let’s be real, one accidental click from an over-permissioned user can lead to disaster.

The Three Key Pieces of RBAC

Azure RBAC is built on three main pieces:

  1. Roles: These define what someone can do. Examples:
    • Owner – The boss. Can do anything and everything.
    • Contributor – Can create and manage resources but can’t assign roles.
    • Reader – Can look, but not touch.
    • Custom Roles – If the built-in roles aren’t enough, you can create your own.
  2. Scope: This defines where the role applies. It can be at:
    • Subscription level (the whole kingdom)
    • Resource group level (a city inside the kingdom)
    • Specific resources (a single castle or shop)
  3. Assignments: This is the who gets what role part. Assign a user, group, or service principal to a role at a given scope, and boom—permissions granted.

Real-World Example: The Coffee Shop Analogy ☕

Imagine you’re running a coffee shop:

  • The Owner (you) can do everything—order supplies, hire staff, make coffee, or even shut down the store.
  • The Baristas (contributors) can make coffee and manage the store but can’t hire or fire anyone.
  • The Customers (readers) can look at the menu, enjoy their coffee, but they’re not allowed behind the counter.

That’s Azure RBAC in action. Everyone gets access to what they need, but no one is accidentally pressing the “shutdown entire store” button.


Common RBAC Mistakes (And How to Avoid Them)

  1. Giving Everyone Owner or Contributor Roles – That’s like handing out master keys to your entire office. Keep permissions minimal!
  2. Not Using Groups – Assigning roles individually? Big mistake. Use Azure AD groups to manage permissions efficiently.
  3. Ignoring Scope – Always assign roles at the lowest necessary level to avoid over-permissioning.
  4. Forgetting to Review Roles Regularly – People leave jobs, projects change, and roles should be updated accordingly.

Final Thoughts: Lock It Down, But Keep It Practical

Azure RBAC is all about control, security, and making sure the right people have the right access. It’s not just an IT thing—it’s about keeping your cloud environment safe and sane.

So next time you’re setting up roles in Azure, ask yourself:

  • Does this person really need this level of access?
  • Could I use a lower scope?
  • Am I following best practices?

Get it right, and your cloud stays secure. Get it wrong, and… well, let’s just say you don’t want to be the person who accidentally gives the intern the power to delete the company’s entire infrastructure.

Thank you for stopping by.✌

Power BI – Restore Datasets to new on-premise Gateway when old Gateway has failed or Recovery Key is lost

Power BI on-premises data gateway is a service running on a Windows server working as a connecting platform between the Power BI cloud service and the on-premise data sources.

Setting up a data gateway on-premise is fairly a straightforward process. There can be instances where your on-premise gateway fails because of a hardware failure, issues due to updates or you may want to move the gateway instance to a new server then you realize you need the recovery key which is no where to be found.

Without a functioning gateway, the reports and dashboard in the Power BI cloud service with datasets that are connected to on-premise data sources will fail resulting in data to become stale. I’ll elaborate more on this issue in this post on how to restore datasets from an old or failed on-premise gateway to a new gateway.

I faced a similar scenario recently and it was a great learning experience. There are few methods using which you can resolve this issue. I’ll try to cover them all in as much detail as possible.

Manual Method

Well.. If you don’t have too many data sources on-premise or if you are just planning for a quick fix maybe because someone important in your organization needs this fixed and they notified you like an hour before their big meeting.

Here are the high-level steps,

Once you install and configure the data gateway, you can see and manage both the old and new instances from the Power BI portal.

To add a user as admin to the gateway in the portal, follow below steps.

This image has an empty alt attribute; its file name is image-15-1024x370.png

Search user using username or email address, select Admin and click Share.

This image has an empty alt attribute; its file name is image-16-1024x504.png

Now to add a new data source, from the page header in the Power BI service, select Settings gear icon > Manage gateways.

I have highlighted my failed gateway and the new gateway server in my case.

Your next step is to determine the data source of the affected dataset. To get this information, you’ll need access to the workspace. As you can see, I have a report named ‘AdventureWorksProducts‘ and the underlying dataset with the same name.

Under the Gateway connection section, you’ll find the necessary information to setup the data source in the new gateway.

Back in the Manage Gateways page and in the Data sources tab, Click on New

Choose the new gateway to create the connection on, then select the Data source type. In my scenario, I picked SQL Server.

Once you provide all the information, Select Create. You see Created New data source if the process succeeds and a new data source entry like in screenshot below.

If you’ve made it this far, you are almost at the end of this method. Now back to the dataset’s settings like we did earlier and on to the Gateway connection section. As a reminder, you’ll need access(Admin, Member or Contributor) to the workspace and to the dataset, also keep in mind that you also need admin permissions on the gateway.

You should see the new data source we created listed. Select it from the drop-down and click Apply

That should take care of the connection and to confirm, you can refresh your dataset to make sure the connection works ok.

Like I said earlier, this method should be good in a small environment or if you are in a hurry to get it fixed and worry about the bulk of things later. I’ll cover the semi-automated way in the coming sections. I use the word automated loosely here but it’s more like less clicks and not moving around in the BI portal as much.

Using a Service Account

In this method, I’m using a service account or in other words a regular user account without any roles assigned to it. This can be an AD synced account or a Azure AD cloud only account. This account will need a Power BI Pro license assigned to it.

Here are the high-level steps,

I’ve already covered the adding data source part to the gateway in the earlier section and the process is same for this method too. You can do it with PowerShell or REST APIs but I don’t believe there is a method to copy the data sources from one gateway to another.

Permissions

In this method, I’m using a service account which was granted Admin permissions for the gateways and set as Owner on the data source. You should be able to get away with just having the account set as user on the data source. This service account is also set as Admin on the workspace but Member or Contributor should do the trick.

You can grant the gateway admin permission in the portal which I’ve covered in the earlier method or use the below script to add the user as admin.

Connect-AzureAD
Connect-DataGatewayServiceAccount
Get-DataGatewayAccessToken

Get-DataGatewayCluster
$gw = Read-Host "Enter Gateway ID"
$user = Read-Host "Enter username to be added as gateway admin"
$userToAdd = (Get-AzureADUser -Filter "userPrincipalName eq '$user'").ObjectId
Get-DataGatewayRegion
$Region = Read-Host "Enter region value where IsDefaultPowerBIRegion is set to true"
Add-DataGatewayClusterUser -GatewayClusterId $gw -PrincipalObjectId $userToAdd -AllowedDataSourceTypes $null -Role Admin -RegionKey $Region

With all these permissions, the service account still needs to take ownership of the dataset to finish rebinding the data source to the new gateway. You won’t have to manually take ownership of the dataset, the script below will do it for you on the dataset you specify.

Rebind dataset

Before proceeding further make sure you have the Microsoft Power BI Cmdlets for PS installed and logged in to the Power BI service using PowerShell,

Connect-PowerBIServiceAccount
Get-PowerBIAccessToken

I don’t do Power BI administration on a daily basis and there was a learning curve for me to understand the inner workings. Here is the thought process that went into building this script.

  1. Get all the gateways the service account has access to
    • Using the output, determine and copy the new gateway ID and store it in a variable
  2. Using the variable from earlier step, return a list of data sources from the new gateway
    • Using the output, determine and copy the data source ID where the affected dataset should be mapped to and store it in a variable
  3. Returns a list of workspaces the user has access to
    • Using the output, determine and copy the workspace ID which has the affected dataset
  4. Using the variable from earlier step, return list of datasets from the specified workspace
    • Using the output, determine and copy the affected dataset’s ID
  5. Using the variable from step 3 and step 4, transfer ownership over the specified dataset to the service account
  6. Using variable from steps 1, 2, 3 and 4, bind the specified dataset from the specified workspace to the new gateway
$gateways = Invoke-PowerBIRestMethod -Url "gateways" -Method Get | ConvertFrom-Json
$gateways.value
Write-Host "Please copy the new Gateway ID from above output" -ForegroundColor Red
$newGWID = Read-Host "Please paste the new Gateway ID"

$GWdatasources = Invoke-PowerBIRestMethod -Url "gateways/$($newGWID)/datasources" -Method Get | ConvertFrom-Json
$GWdatasources.value
Write-Host "Please note down the Data Source ID used by the dataset that needs to be migrated from above output" -ForegroundColor Red
$datasourceObjectIds = Read-Host "Please paste the Data source ID"

$ws = Invoke-PowerBIRestMethod -Url 'groups' -Method Get | ConvertFrom-Json
$ws.value
Write-Host "Please note down the Workspace ID which has the dataset that needs to be migrated from above output" -ForegroundColor Red
$wsID = Read-Host "Please paste the Workspace ID"

$dataset = Invoke-PowerBIRestMethod -Url "groups/$($wsID)/datasets" -Method Get | ConvertFrom-Json
$dataset.value
Write-Host "Please note down the dataset ID that needs to be migrated from above output" -ForegroundColor Red
$dsID = Read-Host "Please paste the dataset ID"

#This below line is not needed if the service account already has ownership of the dataset and is safe to comment out
Invoke-PowerBIRestMethod -Url "https://api.powerbi.com/v1.0/myorg/groups/$($wsID)/datasets/$($dsID)/Default.TakeOver" -Method POST

try { $body = "{
  'gatewayObjectId': '$newGWID',
  'datasourceObjectIds': [
    '$datasourceObjectIds'
  ]
}"

Invoke-PowerBIRestMethod -Url "https://api.powerbi.com/v1.0/myorg/groups/$($wsID)/datasets/$($dsID)/Default.BindToGateway" -Body $body -Method POST
Write-Host "Dataset updated" }

catch {
  Write-Host "An error occurred"
}

You can adjust this script according to your needs as in some instances, your gateway ID, new data source ID and workspace ID will be the same, only the affected dataset ID will vary.

Using a Service Principal

In this method, I’m using a service principal to accomplish the same as above. One added advantage of using this method is, the Power BI Dataset can be setup to refresh without an actual user account. This would be great from an automation point of view and to avoid being tied to a specific user.

Here are the high-level steps,

Create SPN

The az ad app is part of Azure CLI and not a PS cmdlet. You’ll need to have Azure CLI installed and do az login as well before running this.

Connect-AzureAD 
Connect-AzAccount
az login

You can create an Azure AD application which will be the service principal from the portal and grant the and grant the ‘Dataset.ReadWrite.All’ API permission or use the below lines to create it. I’ve detailed how to determine the API ID and Permission ID in this blog post here.

A new Azure AD group is also needed and the Azure AD application has be made a member of this group. The below lines will accomplish that and if you have an existing group you have in mind, you can use that too. I’ll go over the reason for creating this group later in this section.

$appname = Read-Host "Enter a name Azure AD Application's Display Name"
$ObjID = New-AzureADApplication -DisplayName $appname | Select ObjectId
Add-AzADAppPermission -ObjectId $ObjID.ObjectId -ApiId 00000009-0000-0000-c000-000000000000 -PermissionId 322b68b2-0804-416e-86a5-d772c567b6e6 -Type Scope
Start-Sleep -Seconds 60
az ad app permission admin-consent --id $ObjID.ObjectId
Get-AzureADApplication -Filter "DisplayName eq '$appname'" | fl

$grpName = Read-Host "Enter a name for new Azure AD group"
$grpID = (New-AzureADGroup -DisplayName $grpName -MailEnabled $false -SecurityEnabled $true -MailNickName "NotSet").ObjectId
Get-AzureADGroup -ObjectId $grpID
Add-AzureADGroupMember -ObjectId $grpID -RefObjectId $spnToAdd
Get-AzureADGroupMember -ObjectId $grpID

The Get-AzureADApplication cmdlet will list the API permissions we applied. This can be verified in the ‘App registrations‘ blade from the Azure AD portal too.

Create a new Secret in this Azure AD application. You can also achieve this by using PowerShell. This secret value is needed for authentication while running the script later this section.

Remember to copy the secret value as it’ll be masked forever.

And we can also make sure of the group we created and it’s membership. I named the group, ‘PBI-API‘ in Azure AD.

For an Azure AD app to be able to access the Power BI content and APIs, the following settings need to be enabled in Azure AD portal. This is where the Azure AD group comes into play.

Go to Tenant settings in the Power BI Admin portal, and scroll down to Developer settings

  • Enable the Allow service principals to use Power BI APIs
  • Enable the Allow service principals to create and use profiles

Create SPN profile

I noticed that the SPN way of doing things worked in one instance without having a service principal profile created by the service principal. Profiles can be created using Profiles REST API. I’ve included the below lines which will create a profile for the SPN.

$prof = Read-Host "Enter a name for SPN's profile"

$body = "{
    'displayName' : '$prof'
}"

Invoke-PowerBIRestMethod -Url 'https://api.powerbi.com/v1.0/myorg/profiles' -Body $body -Method POST

A service principal can also call GET Profiles REST API to get a list of its profiles.

Invoke-PowerBIRestMethod -Url 'profiles' -Method Get

Permissions

Next, the service principal needs permissions on the dataset. We can achieve this by granting permissions to the service principal on the workspace.

Note: Adding the Azure AD group that has SPN as members doesn’t work

This next step is kind of where things get tricky.

What are we trying to achieve here?

  • Grant the service principal, admin permissions on the new gateway
  • Grant the service principal, user permissions on the gateway data source

Reason why it is tricky is, I first tried adding the Azure AD group the above permissions and it allowed me to add it but the script which comes later in this section didn’t work as expected. Based on further research, I realized that the SPN needs to be granted the above access directly instead of using the Azure AD group. Also, at the time of writing this post, adding SPN the above permissions using the portal is not supported. Hence, we’ll have to use PowerShell cmdlets,

Before proceeding further, please connect to the AzAccount and PowerBIService using the below cmdlets,

Connect-AzAccount
Connect-PowerBIServiceAccount
Get-PowerBIAccessToken

The below script will add the permissions I mentioned above and display the same at the end of executing the cmdlets. One good thing about the part where you add permissions to the gateway, data sources and workspaces is, it is a one-time deal.

Get-DataGatewayCluster
$gw = Read-Host "Enter Gateway ID"
$spn = Read-Host "Enter App name to be added as gateway admin"
$spnToAdd = (Get-AzADServicePrincipal -DisplayName $spn).Id
Get-DataGatewayRegion
$Region = Read-Host "Enter region value where IsDefaultPowerBIRegion is set to true"
Add-DataGatewayClusterUser -GatewayClusterId $gw -PrincipalObjectId $spnToAdd -AllowedDataSourceTypes $null -Role Admin -RegionKey $Region
Get-DataGatewayCluster -GatewayClusterId $gw | Select -ExpandProperty Permissions | ft
Get-DataGatewayClusterDatasource -GatewayClusterId $gw
$gwDSID = Read-Host "Enter Gateway Cluster DatasourceId"
Add-DataGatewayClusterDatasourceUser -GatewayClusterId $gw -GatewayClusterDatasourceId $gwDSID -DatasourceUserAccessRight Read -Identifier $spnToAdd
Get-DataGatewayClusterDatasourceUser -GatewayClusterId $gw -GatewayClusterDatasourceId $gwDSID

With all the permissions for the SPN now in place, we are ready to take ownership of the affected datasets in the workspaces and bind it with the new data source on the new gateway

Rebind dataset

In this SPN method, Instead of logging in with a username and password, you’ll have to login with the Application ID and secret

$Tenant = Read-Host "Enter Azure AD Tenant ID"
Connect-PowerBIServiceAccount -Tenant $Tenant -ServicePrincipal -Credential (Get-Credential) #user = Application (client) ID | Password is the secret value we created earlier in this section
Get-PowerBIAccessToken

The script is pretty much the same as in earlier section but only runs in the SPN context.

$gateways = Invoke-PowerBIRestMethod -Url "gateways" -Method Get | ConvertFrom-Json
$gateways.value
Write-Host "Please copy the new Gateway ID from above output" -ForegroundColor Red
$newGWID = Read-Host "Please paste the new Gateway ID"

$GWdatasources = Invoke-PowerBIRestMethod -Url "gateways/$($newGWID)/datasources" -Method Get | ConvertFrom-Json
$GWdatasources.value
Write-Host "Please note down the Data Source ID used by the dataset that needs to be migrated from above output" -ForegroundColor Red
$datasourceObjectIds = Read-Host "Please paste the Data source ID"

$ws = Invoke-PowerBIRestMethod -Url 'groups' -Method Get | ConvertFrom-Json
$ws.value
Write-Host "Please note down the Workspace ID which has the dataset that needs to be migrated from above output" -ForegroundColor Red
$wsID = Read-Host "Please paste the Workspace ID"

$dataset = Invoke-PowerBIRestMethod -Url "groups/$($wsID)/datasets" -Method Get | ConvertFrom-Json
$dataset.value
Write-Host "Please note down the dataset ID that needs to be migrated from above output" -ForegroundColor Red
$dsID = Read-Host "Please paste the dataset ID"

Invoke-PowerBIRestMethod -Url "https://api.powerbi.com/v1.0/myorg/groups/$($wsID)/datasets/$($dsID)/Default.TakeOver" -Method POST

try { $body = "{
  'gatewayObjectId': '$newGWID',
  'datasourceObjectIds': [
    '$datasourceObjectIds'
  ]
}"

Invoke-PowerBIRestMethod -Url "https://api.powerbi.com/v1.0/myorg/groups/$($wsID)/datasets/$($dsID)/Default.BindToGateway" -Body $body -Method POST
Write-Host "Dataset updated" }

catch {
  Write-Host "An error occurred"
}

Similar to the earlier section, you can adjust this script according to your needs as in some instances, your gateway ID, new data source ID and workspace ID will be the same, only the affected dataset ID will vary.

Needless to say, you can test if this was successful by doing a ‘Refresh now‘ on the dataset.

Issues you may encounter and How to fix it

Issue: You may encounter below status codes while running the Invoke-PowerBIRestMethod

Response status code : 404 (Not Found)
Response status code : 400 (Bad Request)

Fix or workaround: Well.. If you’ve already browsed though community.powerbi.com, then might have already realized that you are not alone dealing with these error codes. Usually this means you are requesting the Power BI REST API endpoints for data that doesn’t exist or you or the SPN that’s requesting the resource doesn’t have the necessary permissions to it. These best way to troubleshoot is to run these requests one at a time to determine where you it is failing or understand which resource you don’t have permissions to.

Issue: Applied permissions don’t reflect in the portal

Fix or workaround: I noticed that some of the changes takes time. Give it a few minutes before you go changing more things and you lose track of all the things you’ve changed in the process. If the permissions still didn’t show up for a while, use PowerShell cmdlets to verify if the permissions you’ve set was applied or not.

I’ll keep experimenting other scenarios and I’ll update the issues I come across later on.

This was one of those really lengthy posts but hey..as long as there is a solution at the end..Hopefully..am I right?..😁🤷‍♂️

Thank you for stopping by.✌

Azure AD – Improve Authenticator Notifications with Additional Context and Number Matching

As I have covered several times before, disabling basic authentication in one of the best things you can do in your O365 tenant for security.

MFA helps protect user’s account and prevents attacks. It is not perfect by any means but it is being improved. I’m a big fan of the Authenticator App. I try not to use the SMS or voice call options. Whenever I get a chance I always advocate the users I work with, to stick with the App. If your organization is yet to roll out MFA, it is time to take a hard look and make some drastic changes.

Microsoft in their November 18 Azure AD Identity blog revealed two new features for the Authenticator app. IMO, all O365 tenants should strongly consider enabling these two features below.

  • Number matching in Microsoft Authenticator
  • Additional context in Microsoft Authenticator

Number Matching

When a user responds to MFA challenge, they will see a number in the application or in the webpage which is challenging them and the user must enter this number in the Authenticator app to complete the process. This process is already part of the passwordless authentication method.

Additional Context

The Authenticator will also display the name of the app requesting MFA and also the user’s sign-in location. The sign-in location is based on the user’s public IP address. The location may not be accurate at times. This is because the IP location tagging and based on what I saw it is not the exact location of where the application’s traffic origin but usually close enough.

Application prompt on the webpage
Authenticator prompt

How to enable number matching with additional context in Azure AD

  • Open Azure AD admin center(https://aad.portal.azure.com/)
  • Click on the Security tab –> Authentication methods
  • Select Microsoft Authenticator
  • Toggle ENABLE to Yes
  • Toggle TARGET to All users
    • Depending on how you decide to roll out this feature, you can select a Azure AD group by selecting Select users, Select the group and follow along the next steps
  • Click on the three dots and Configure
  • Set
    • Authentication mode = Any
    • Require number matching = Enabled
    • Show additional context in notifications = Enabled
  • Click Done
  • Click Save
Microsoft Authenticator settings

Configure settings for All Users

In the drop down for ‘Require number matching’ and ‘Show additional context in notifications’, there is a ‘Microsoft Managed‘ option. It means this functionality will be enabled by default for all tenants after the feature is generally available. Currently it is in public preview.

Thank you for stopping by.✌

Azure AD – Assign Groups and Users to an application

Azure AD allows granting access to resources by providing access rights to a single user or to an entire Azure AD group. Using groups let the application or the resource owner to assign a set of permissions to all the members of a group. Management rights can be granted to other roles, like example., Helpdesk administrators to add or remove members from the group.

When a group is assigned to an application, only users in the group will have access. Also, if the application exposes role, roles can also be assigned to groups or users.

When I was working on integrating Salesforce with Azure AD for SSO, I needed to assign groups to the roles that Salesforce exposed and I figured I’d document the process I went though here.

Bulk create Azure AD groups

This section describes how to create multiple groups in Azure AD. This is not needed if your organization already has groups created.

Use below script to create multiple Azure AD groups that are listed in a csv file,

Connect-AzureAD
$groups = import-csv "C:\tmp\AzureAD Groups\groups.csv"

Foreach($group in $groups) {

New-AzureADGroup -DisplayName $group.name -Description $group.description -MailEnabled $false -SecurityEnabled $true -MailNickName "NotSet"

}

csv file input,

csv file

PowerShell output,

output

Assign Groups and Users to an app using PowerShell

Assigning groups or users can be done from the Azure AD admin portal by clicking on the Users and groups tab in the application which you are granting access to.

My plan here is to create Azure AD groups that corresponds to the name of the role that Salesforce exposes and then add users to those groups which provides them with appropriate access to the application.

Determine the roles available for the application

To determine the roles that the application exposes, use the cmdlet below.

$appname = Read-Host "Enter your App's Display Name"
$spo = Get-AzureADServicePrincipal -Filter "Displayname eq '$appname'"
$spo.AppRoles | ft DisplayName,IsEnabled,Id
AppRoles Output

Assign Groups to Roles in Application

Use below script to assign the application’s roles to groups. If you notice the csv file, I’m using the groups created in the previous step to the roles. This way, it is easier to manage. The New-AzureADGroupAppRoleAssignment cmdlet can be used to achieve this.

$appname = Read-Host "Enter your App's Display Name"
$spo = Get-AzureADServicePrincipal -Filter "Displayname eq '$appname'"
$groups = import-csv "C:\tmp\Salesforce_Asgn\groups.csv"

Foreach($group in $groups) {
	$id = Get-AzureADGroup -SearchString $group.name
	$app_role_name = $group.role
	$app_role = $spo.AppRoles | Where-Object { $_.DisplayName -eq $app_role_name }
	New-AzureADGroupAppRoleAssignment -ObjectId $id.ObjectId -PrincipalId $id.ObjectId -ResourceId $spo.ObjectId -Id $app_role.Id
	
}
csv input
PowerShell output

This below is how the application looks like in the Azure AD admin portal after running the above script,

Application Users and groups tab

Assign Users to Roles in Application

Use below script to assign the application’s roles to users. This can be achieved using the New-AzureADUserAppRoleAssignment cmdlet. Use the below script,

$appname = Read-Host "Enter your App's Display Name"
$spo = Get-AzureADServicePrincipal -Filter "Displayname eq '$appname'"
$users = import-csv "C:\tmp\Salesforce_Asgn\users.csv"

Foreach($user in $users) {
	$id = Get-AzureADUser -ObjectId $user.name
	$app_role_name = $user.role
	$app_role = $spo.AppRoles | Where-Object { $_.DisplayName -eq $app_role_name }
	New-AzureADUserAppRoleAssignment -ObjectId $id.ObjectId -PrincipalId $id.ObjectId -ResourceId $spo.ObjectId -Id $app_role.Id
	
}
PowerShell Output
Application Users and groups tab

Get all role assignments to an application using PowerShell

Get-AzureADServiceAppRoleAssignment cmdlet can be used to determine all role assignments to an application,

$appname = Read-Host "Enter your App's Display Name"
$spo = Get-AzureADServicePrincipal -Filter "Displayname eq '$appname'"
Get-AzureADServiceAppRoleAssignment -ObjectId $spo.ObjectId -All $true
PowerShell Output

Remove All Groups and Users assigned to an application

To remove all assigned groups and users from an application, Remove-AzureADServiceAppRoleAssignment cmdlet can be used,

$appname = Read-Host "Enter your App's Display Name"
$spo = Get-AzureADServicePrincipal -Filter "Displayname eq '$appname'"
$app_assignments = Get-AzureADServiceAppRoleAssignment -ObjectId $spo.ObjectId -All $true
$app_assignments | ForEach-Object {
	if ($_.PrincipalType -eq "user") {
		Remove-AzureADUserAppRoleAssignment -ObjectId $_.PrincipalId -AppRoleAssignmentId $_.ObjectId
	} elseif ($_.PrincipalType -eq "Group") {
		Remove-AzureADGroupAppRoleAssignment -ObjectId $_.PrincipalId -AppRoleAssignmentId $_.ObjectId
	}
}

It should go without saying that removing all permissions will disable user’s access to the application. Don’t try this as a first step in a production environment, unless you are absolutely sure of it.

Thank you for stopping by.✌