Tuesday, December 3, 2024

Connect to Azure PowerShell with Conditional Access Authentical Context

You can require users who are eligible for a role to satisfy Conditional Access policy requirements. For example, you can require users to use a specific authentication method enforced through Authentication Strengths, elevate the role from an Intune-compliant device, and comply with terms of use. Learn more here https://learn.microsoft.com/en-us/entra/id-governance/privileged-identity-management/pim-resource-roles-configure-role-settings#on-activation-require-microsoft-entra-conditional-access-authentication-context 

However, once this is enabled, users cannot activate their eligible roles using Azure PowerShell since there is no way to login to Azure PowerShell with authentication context. 

To solve this issue, you can first acquire a token with authentication context and use it to connect to Azure PowerShell.

First, remember to disconnect so an older token is not used by Azure PowerShell

DisConnect-AzAccount

Now, acquire a token with authentication context. Replace c1 with the id of your authentication context. Learn more here https://learn.microsoft.com/en-us/entra/identity/conditional-access/concept-conditional-access-cloud-apps#configure-authentication-contexts 

$MsResponse = Get-MSALToken -Scopes @("https://management.core.windows.net//.default openid profile offline_access") -ClientId "04b07795-8ddb-461a-bbee-02f9e1bf7b46" -RedirectUri "http://localhost:8400/" -Authority "https://login.microsoftonline.com/common" -Interactive -ExtraQueryParameters @{claims='{"access_token":{"xms_cc":{"values":["CP1"]},"acrs":{"essential":true, "value":"c1"}}}'} 

Connect to Azure PowerShell with the acquired access token and provide the upn of the user if prompted for AccountId

Connect-AzAccount -AccessToken $MsResponse.AccessToken 

Activate your eligible role. Replace $scope, $role and $principal with your values. Learn more here https://learn.microsoft.com/en-us/powershell/module/az.resources/new-azroleassignmentschedulerequest?view=azps-13.0.0#example-3-activate-a-new-role-assignment-schedule-request-as-user 

$guid = (New-Guid).Guid 

$startTime = Get-Date -Format o 

$scope = "/subscriptions/c896b064-0cd9-49d5-a7df-c82df3dc60f3" 

$role = "/subscriptions/c896b064-0cd9-49d5-a7df-c82df3dc60f3/providers/Microsoft.Authorization/roleDefinitions/18d7d88d-d35e-4fb5-a5c3-7773c20a72d9" 

$principal = "290190c3-1372-4076-99a5-9efa5a1a18e3" 

New-AzRoleAssignmentScheduleRequest -Name $guid -Scope $scope -ExpirationDuration PT1H -ExpirationType AfterDuration -PrincipalId $principal -RequestType SelfActivate -RoleDefinitionId $role -ScheduleInfoStartDateTime $startTime -Justification "test"