Monday, September 8, 2025

Entra ID Multi Tenant App custom scope approval PowerShell script

 $myApiSp = Get-MgServicePrincipal -Filter "displayName eq 'MultitenantApplication'"

# Or by AppId if displayName is not unique or known
# $myApiSp = Get-MgServicePrincipal -Filter "appId eq 'your-my-api-app-id'"

if (-not $myApiSp) {
    Write-Error "Could not find Service Principal for 'My API Application Name'. Ensure it's correctly registered."
    return
}

$externalAppSp = Get-MgServicePrincipal -Filter "displayName eq 'MultitenantApplication'"
# Or by AppId
# $externalAppSp = Get-MgServicePrincipal -Filter "appId eq 'external-multi-tenant-app-id'"

if (-not $externalAppSp) {
    Write-Error "Could not find Service Principal for 'External Multi-Tenant App Name'. Ensure it has been consented to in your tenant."
    return
}

# Get the App Roles (Application Permissions) exposed by My API
$myApiSp.AppRoles | Format-Table Id, DisplayName, Value, IsEnabled

# Pick the 'Id' of the specific scope you want to grant, e.g., for 'MyAPI.ReadData'
# For App Role (Application Permission)
$appRoleIdToGrant = ($myApiSp.AppRoles | Where-Object Value -eq "MyAPI.ReadData").Id

$params = @{
    "principalId" = $externalAppSp.Id
    "resourceId"  = $myApiSp.Id
    "appRoleId"   = $appRoleIdToGrant # The ID of the app role you want to grant
}
New-MgServicePrincipalAppRoleAssignment -ServicePrincipalId $externalAppSp.Id -BodyParameter $params
Write-Host "Application permission granted for $($externalAppSp.DisplayName) to $($myApiSp.DisplayName) app role $($appRoleIdToGrant)."

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"