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"
}
}
No comments:
Post a Comment