Friday, February 14, 2020

Connect to Azure AD PowerShell with MFA

Sometimes you might want to connect to Azure AD PowerShell with MFA but there is no way for the PowerShell to prompt you for MFA unless you have MFA enforced on the account.

The scenario which I had was calling a cmdlet for Privileged Identity Management where I was activating a role which requires MFA

The solution is to get an access token with MFA and pass the token while connecting to PowerShell.

The pre-requisite is that you have already installed Azure AD PowerShell by following these steps

# Install
if(!(Get-Module | Where-Object {$_.Name -eq 'PowerShellGet' -and $_.Version -ge ''})) { Install-Module PowerShellGet -Force }
if(!(Get-Package { Install-Package }

# Get token for MS Graph by prompting for MFA
$MsResponse = Get-MSALToken -Scopes @("") -ClientId "1b730954-1685-4b74-9bfd-dac224a7b894" -RedirectUri "urn:ietf:wg:oauth:2.0:oob" -Authority "" -Interactive -ExtraQueryParameters @{claims='{"access_token" : {"amr": { "values": ["mfa"] }}}'}

# Get token for AAD Graph
$AadResponse = Get-MSALToken -Scopes @("") -ClientId "1b730954-1685-4b74-9bfd-dac224a7b894" -RedirectUri "urn:ietf:wg:oauth:2.0:oob" -Authority ""

Connect-AzureAD -AadAccessToken $AadResponse.AccessToken -MsAccessToken $MsResponse.AccessToken -AccountId: "upn" -tenantId: "tenantId"

# Call cmdlet which requires MFA
$resource = Get-AzureADMSPrivilegedResource -ProviderId AadRoles

$roleDefinition = Get-AzureADMSPrivilegedRoleDefinition  -ProviderId AadRoles -ResourceId $resource.Id -Filter "DisplayName eq 'Global Administrator'"

$subject = Get-AzureADUser -Filter "userPrincipalName eq 'upn'"

$schedule = New-Object Microsoft.Open.MSGraph.Model.AzureADMSPrivilegedSchedule
$schedule.Type = "Once"
$schedule.StartDateTime = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ")

Open-AzureADMSPrivilegedRoleAssignmentRequest -ProviderId AadRoles -Schedule $schedule -ResourceId $resource.Id -RoleDefinitionId $roleDefinition.Id -SubjectId $subject.ObjectId -AssignmentState "Active" -Type "UserAdd" -Reason "Test"

No comments:

Post a Comment