Wednesday, September 18, 2024

Create the Azure B2C Local accounts in bulk

Creating Azure B2C local accounts with randomly generated passwords- 

# Install required modules (if not already installed)

Import-Module Microsoft.Graph

Import-Module ImportExcel


# Variables

$clientId = "<<clientid>>"

$clientSecret = "<<clientsecret>>"

$tenantId = "<<tenantid>>"

$issuerDomain = "<<domain>>.onmicrosoft.com"  # The Azure B2C issuer domain


# FilePath to your Excel file

$excelFilePath = "C:\Stage\PowershellScript\users.xlsx"

$logFilePath = "C:\Stage\PowershellScript\logfile.txt"


# Function to authenticate and get an access token

function Get-GraphAccessToken {

    $body = @{

        client_id     = $clientId

        scope         = "https://graph.microsoft.com/.default"

        client_secret = $clientSecret

        grant_type    = "client_credentials"

    }


    $tokenResponse = Invoke-RestMethod -Method Post -Uri "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token" -ContentType "application/x-www-form-urlencoded" -Body $body

    return $tokenResponse.access_token

}


# Function to create a user in Azure B2C

function Create-B2CUser($accessToken, $firstName, $lastName, $email, $password) {

    $userPayload = @{

        accountEnabled = $true

        displayName = "$firstName $lastName"

        givenName = $firstName

        surname = $lastName

        mailNickname = $email -replace "@", "-"

        mail = $email

        passwordProfile = @{

            forceChangePasswordNextSignIn = $true

            password = $password

        }

        identities = @(

            @{

                signInType = "emailAddress"

                issuer = $issuerDomain

                issuerAssignedId = $email

            }

        )

    }


    $jsonPayload = $userPayload | ConvertTo-Json -Depth 10

    $uri = "https://graph.microsoft.com/v1.0/users"


    $headers = @{

        "Authorization" = "Bearer $accessToken"

        "Content-Type" = "application/json"

    }


    $response = Invoke-RestMethod -Method Post -Uri $uri -Headers $headers -Body $jsonPayload

    return $response

}


# Generate a random strong password

function Generate-StrongPassword {

    return [System.Web.Security.Membership]::GeneratePassword(12, 4)

}


# Function to write logs to a file

function Write-Log($message) {

    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"

    $logMessage = "$timestamp - $message"

    Add-Content -Path $logFilePath -Value $logMessage

}


# Get access token

$accessToken = Get-GraphAccessToken


# Read Excel file and create users

$users = Import-Excel -Path $excelFilePath


foreach ($user in $users) {

    $firstName = $user.FirstName

    $lastName = $user.LastName

    $email = $user.Email

    $password = Generate-StrongPassword


    try {

        $response = Create-B2CUser -accessToken $accessToken -firstName $firstName -lastName $lastName -email $email -password $password

        $successMessage = "Successfully created user: $($response.displayName) ($email)"

        Write-Host $successMessage

        Write-Log $successMessage

    }

    catch {

        Write-Host "Error creating user $email"

        Write-Log "Error creating user $email"

    }

}


Wednesday, August 14, 2024

Powershell script to read the groups using Get-MgGroup

# Step 1: Define the client credentials

$clientId= "<<client id>>"

$tenantId= "<<tenant id>>"

$clientSecret = ConvertTo-SecureString "<<client secret>>" -AsPlainText -Force


 # Step 2: Create the PSCredential object

$credential = New-Object System.Management.Automation.PSCredential($clientId, $clientSecret)


Connect-MgGraph -Credential $credential -TenantId $tenantId


# Retrieve all groups with preferred properties

$groups = Get-MgGroup -All -Property Id, DisplayName, OnPremisesSyncEnabled, mail


# Define the output file path

$excelFilePath = "C:\AzureGroupsExport\AzureADGroups.xlsx"


# Export the groups to Excel

$groups | Select-Object Id, DisplayName, OnPremisesSyncEnabled, mail | Export-Excel -Path $excelFilePath -WorksheetName "AzureADGroups" -AutoSize


# Notify the user

Write-Output "Groups have been exported to $excelFilePath"

Saturday, February 17, 2024

Powershell script to check B2B guest account invitation state in bulk

 # Install AzureAD module if not already installed

Install-Module -Name AzureAD -Force -Scope CurrentUser

# Import required modules

Import-Module AzureAD

# Read emails from Excel sheet

$emails = Import-Excel -Path "emails.xlsx" | Select-Object -ExpandProperty Email

# Connect to Azure AD

Connect-AzureAD

# Iterate through emails and check user existence and account status

foreach ($email in $emails) {

    $user = Get-AzureADUser -Filter "mail eq '$email'"

    if ($user) {

        Write-Host "User with email $email exists. Account Enabled: $($user.AccountEnabled) with invitation status: $($user.UserState)"

    } else {

        Write-Host "User with email $email does not exist."

    }

}


Tuesday, January 16, 2024

How to schedule Azure APIM instance backup

In this article we will go through high level steps to take backup of Azure APIM instance to a storage account.

There are couple of ways to configure a regular backup of the Azure APIM instances. In this instance, we will configure Azure APIM backup using Logic Apps.

Before we proceed make sure below services are are already created

1. Azure APIM instance

2. Azure Storage account

3. Container in Azure Storage account

Let's see what it takes to configure a scheduled Azure APIM instance backup on a daily basis

1. Create a Logic App and navigate to Logic App designer tab

2. Add Recurrence step and set interval to what ever you would like to run the backups.

3. Add next step with HTTP POST method and use below URL and replace the place holders as per your environment

https://management.azure.com/subscriptions/<<Subscription ID>>/resourceGroups/<<Resource Group Name>>/providers/Microsoft.ApiManagement/service/<<APIM Instance Name>>/backup?api-version=2021-08-01"

then add below payload in the by replacing the values per your environment

{

"accessKey": "<<Storage Account Access Key>>",
"backupName":"<<Provide the backup name you would like to create with and append the name with date or  current timestamp to make the backup name unique>>",

"containerName":"<<Container Name from the storage account>>"

"storageAccount":"<<Azure Storage account name>>"

}

4. Save the Logic App.

5. Now, Enabled the System assigned Identity for the logic app

6. Navigate to Azure APIM instance >> Access Control(IAM) tab

7. Click on Add role Assignment then select "API Management Service Contributor" role and click Next

8. Select the "Managed Identity" and select "Select Members"

9. Select the Azure Logic App create above and click on "Review and assign"

10. Back to Azure Logic App and click on "Run" to test the Logic app for Azure APIM backup.

Note that backup will take around 30 min to complete.


Thanks