Achraf Ben Alaya
No Result
View All Result
  • Home
  • News
  • Blog
    • blazor
    • c#
    • Cloud
      • Azure
    • docker
    • sql
    • xamarin
    • Dapr
    • Tricks, Tips and Fixes
    • General Tips & Fix
  • AI
  • Cloud
  • Motivation
  • Courses
  • About
    • Resume
    • Privacy Policy
SUBSCRIBE
  • Home
  • News
  • Blog
    • blazor
    • c#
    • Cloud
      • Azure
    • docker
    • sql
    • xamarin
    • Dapr
    • Tricks, Tips and Fixes
    • General Tips & Fix
  • AI
  • Cloud
  • Motivation
  • Courses
  • About
    • Resume
    • Privacy Policy
No Result
View All Result
Achraf Ben Alaya
No Result
View All Result
ADVERTISEMENT
Home Blog Cloud Azure

Automated Monitoring of Azure App Registration Secrets with Automation Accounts and Logic Apps

achraf by achraf
October 7, 2024
in Azure, Blog, Cloud
4 min read
0
Automated Monitoring of Azure App Registration Secrets with Automation Accounts and Logic Apps
0
SHARES
730
VIEWS
Share on FacebookShare on Twitter

 

As organizations increasingly rely on cloud services, managing application secrets securely becomes crucial. Secrets, such as API keys and authentication credentials, can easily become vulnerabilities if not monitored properly. To address this need, we can utilize PowerShell to automate the process of retrieving and reporting on application secret expiration in Microsoft Azure Active Directory (Azure AD). This blog post outlines a PowerShell script that accomplishes just that.

You can use this repository link to access the whole script and Terraform code needed to construct the resource.

 Overview of the Script ( Automation Accounts )

This PowerShell script connects to Microsoft Graph using app-only authentication, retrieves application registrations, checks their secret expiration dates, and generates a comprehensive HTML report. The report is then sent to a Logic App, which can be used for further processing, such as sending notifications to stakeholders.

Step-by-Step Breakdown of the Script

before we start let’s see what will receive as report :

1. Secure Credential Retrieval:

The script starts by retrieving the Application (Client) ID, Client Secret, and Tenant ID stored in Azure Automation as secure credentials. This ensures that sensitive information remains secure.

$ApplicationClientIddata = Get-AutomationPSCredential -Name 'ApplicationClientId'

2. Convert Secure Strings to Plain Text:

The retrieved secure strings are converted to plain text to facilitate their use in authentication.

$ApplicationClientId = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto(
[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($ApplicationClientIddata.Password)
)

 

3. Connecting to Microsoft Graph:

The script establishes a connection to Microsoft Graph using the provided credentials. This is essential for querying Azure AD for application registrations and their associated secrets.

Connect-MgGraph -TenantId $TenantId -ClientSecretCredential $ClientSecretCredential

 

4. Retrieving Application Registrations:

Once connected, the script retrieves all application registrations in Azure AD. Each application’s details, including its secrets, are then queried.

$Applications = Get-MgApplication -All

 

5. Secret Expiration Check:

The core of the script is a loop that checks the expiration status of each application’s secrets. It calculates how many days are left before each secret expires and categorizes them into three groups: expired, expiring soon (within 90 days), and still valid.

foreach ($Secret in $Secrets) {
$RemainingDaysCount = ($EndDate - $Now).Days
...
}

 

6. Generating an HTML Report:

The script constructs an HTML report summarizing the secret expiration status of all applications. It includes a summary of the total number of applications, counts of expired secrets, and a detailed table displaying individual application details.

$HtmlContent += @"
<h3>Summary</h3>
...
"@

 

7. Sending the Report to Logic App:

Finally, the generated HTML content is converted to JSON and sent to a specified Logic App endpoint for further processing, such as notifications or storage.

$Response = Invoke-RestMethod -Uri $LogicAppUrl -Method Post -Body $JsonPayload -ContentType 'application/json'

 

Benefits of This Script

– Automated Monitoring: By automating the secret expiration checks, organizations can proactively manage application secrets, reducing the risk of security breaches.

– Clear Reporting: The HTML report provides a visually accessible summary of application secret statuses, making it easier for teams to monitor compliance and identify issues.

– Integration with Azure Services: By sending reports to Logic Apps, the script can easily integrate with other Azure services for alerts or workflows, enhancing operational efficiency.

 Overview of the Logic App

The main goal of the logic app for now is the receive the results and send email to certain users .
In the future this will be updated even to send chat in teams and another communication services

{
  "definition": {
    "$schema": "https://schema.management.azure.com/providers/Microsoft.Logic/schemas/2016-06-01/workflowdefinition.json#",
    "contentVersion": "1.0.0.0",
    "triggers": {
      "When_a_HTTP_request_is_received": {
        "type": "Request",
        "kind": "Http",
        "inputs": {
          "schema": {
            "properties": {
              "htmlContent": {
                "type": "string"
              }
            },
            "type": "object"
          }
        }
      }
    },
    "actions": {
      "Send_an_email_(V2)": {
        "type": "ApiConnection",
        "inputs": {
          "host": {
            "connection": {
              "name": "@parameters('$connections')['office365']['connectionId']"
            }
          },
          "method": "post",
          "body": {
            "To": "ben_alaya_achraf@outlook.com",
            "Subject": "updates",
            "Body": "<p class=\"editor-paragraph\">@{triggerBody()?['htmlContent']}</p>",
            "Importance": "Normal"
          },
          "path": "/v2/Mail"
        },
        "runAfter": {}
      }
    },
    "parameters": {
      "$connections": {
        "type": "Object",
        "defaultValue": {}
      }
    }
  },
  "parameters": {
    "$connections": {
      "value": {
        "office365": {
          "id": "/subscriptions/subid/providers/Microsoft.Web/locations/francecentral/managedApis/office365",
          "connectionId": "/subscriptions/subid/resourceGroups/rg-app-registration-001/providers/Microsoft.Web/connections/office365",
          "connectionName": "office365"
        }
      }
    }
  }
}

Terraform

 

resource "azurerm_automation_account" "automation-account" {
  name                = "cloudopsmonitoring-poc-001"
  location            = azurerm_resource_group.inframonitor_prd_rg.location
  resource_group_name = azurerm_resource_group.inframonitor_prd_rg.name
  sku_name            = "Basic"

}


resource "azurerm_logic_app_workflow" "monitoringspn-logic_app_workflow" {
  name                = "logic-monitor-poc-001"
  location            = azurerm_resource_group.inframonitor_prd_rg.location
  resource_group_name = azurerm_resource_group.inframonitor_prd_rg.name

  lifecycle {
    ignore_changes = [
      parameters, workflow_parameters
    ]
  }
}


resource "azurerm_resource_group" "inframonitor_prd_rg" {
  name     = "rg-monitor-poc-001"
  location = "francentral"

}

 

Conclusion

In conclusion, managing application secrets is vital for maintaining security in cloud environments. This PowerShell script provides a robust solution for monitoring secret expiration in Azure AD and generates actionable reports that can help organizations stay ahead of potential security issues. By leveraging automation and Azure services, teams can enhance their security posture while saving time and resources.

Ps : This will be udpates in the future to add the below feature :

  • Scan Certificates too and add to the report
  • Send Report to teams chat
ShareTweet
Previous Post

Dealing with Stuck ‘Signing Out’ Screens on Azure Windows Servers

Next Post

PowerShell Automation for Azure Networks: Detailed VNET and Subnet Analysis

Related Posts

Azure

Honored to be recognized as a Microsoft Azure MVP for 2025-2026

July 20, 2025
28
AI

Model Context Protocol (MCP): The Future of AI Integration

April 21, 2025
197
Azure

Step-by-Step Guide: Azure Front Door + Storage Account Static Website + Custom Domain with Terraform

March 11, 2025
507
Network Security & Route Tables – Checking NSGs, route tables, and service endpoints for a targeted VNET or Subnet
Azure

Network Security & Route Tables – Checking NSGs, route tables, and service endpoints for a targeted VNET or Subnet

February 3, 2025
162
Understanding Generative AI and RAG Benefits
AI

Understanding Generative AI and RAG Benefits

January 12, 2025
121
Azure Communication Services Email Sending Simplified: From Setup to Execution and Monitoring
Azure

Azure Communication Services Email Sending Simplified: From Setup to Execution and Monitoring

December 8, 2024
1.9k
Next Post
PowerShell Automation for Azure Networks: Detailed VNET and Subnet Analysis

PowerShell Automation for Azure Networks: Detailed VNET and Subnet Analysis

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Terraform

Certifications

Microsoft certified trainer (MCT)

Recommended

Dapr – State management (redis)  Part 1/2

Dapr – State management (redis) Part 1/2

August 17, 2021
759
 Azure Container Apps : User-Assigned Identity, ACR, and Key Vault

 Azure Container Apps : User-Assigned Identity, ACR, and Key Vault

November 12, 2023
240
Configure postman / newman API tests in Azure DevOps

Configure postman / newman API tests in Azure DevOps

October 25, 2021
3.5k
Microsoft Ignite Cloud Skills Challenge November 2021 :  Learn…and get rewarded (only 3 days left)

Microsoft Ignite Cloud Skills Challenge November 2021 : Learn…and get rewarded (only 3 days left)

November 27, 2021
295
15 E-books that focus on learning Microsoft Azure Cloud

15 E-books that focus on learning Microsoft Azure Cloud

April 23, 2023
220
How to setup nginx reverse proxy && load balancer for aspnet core apps with Docker and azure kubernetes service (AKS)

How to configure an ingress controller using TLS/SSL for the Azure Kubernetes Service (AKS)

November 25, 2022
2.3k
Facebook Twitter LinkedIn Youtube

Honored to be recognized as a Microsoft Azure MVP for 2025-2026

July 20, 2025

Model Context Protocol (MCP): The Future of AI Integration

April 21, 2025

Step-by-Step Guide: Azure Front Door + Storage Account Static Website + Custom Domain with Terraform

March 11, 2025

Categories

  • AI (2)
  • Apps (1)
  • Azure (64)
  • blazor (2)
  • Blog (91)
  • c# (7)
  • Cloud (66)
  • Courses (3)
  • Dapr (4)
  • docker (4)
  • Games (1)
  • General Tips & Fix (1)
  • Home (1)
  • Kubernetes Service (AKS) (1)
  • motivation (2)
  • Motivation (3)
  • News (9)
  • Resume (1)
  • sql (4)
  • Terrafrom (1)
  • Tricks, Tips and Fixes (4)
  • xamarin (5)
No Result
View All Result
  • Home
  • News
  • Blog
    • blazor
    • c#
    • Cloud
      • Azure
    • docker
    • sql
    • xamarin
    • Dapr
    • Tricks, Tips and Fixes
    • General Tips & Fix
  • AI
  • Cloud
  • Motivation
  • Courses
  • About
    • Resume
    • Privacy Policy