1+ # Replace this with the AppId of the Application you want to enable PreConsent
2+ $appId = " <replace>"
3+
4+ # Start Azure AD PowerShell session
5+ Connect-MsolService
6+
7+ # Fetch your TenantId for querying Graph later
8+ $tenantId = (Get-MsolCompanyInformation ).ObjectId.toString()
9+
10+ # Generate a random guid string
11+ $random = [Guid ]::NewGuid().toString()
12+
13+ # Create a service principal using the random string as DisplayName and Password
14+ $servicePrincipal = New-MsolServicePrincipal - DisplayName $random - Type Password - Value $random
15+
16+ # Assign service principal to Tenant Admin role
17+ Add-MsolRoleMember - RoleName " Company Administrator" - RoleMemberType ServicePrincipal - RoleMemberObjectId ($servicePrincipal.ObjectId )
18+
19+ # Sleep for 30 seconds
20+ Start-Sleep - s 30
21+
22+ # Construct params for auth request
23+ $authParams = @ {grant_type = ' client_credentials' ; client_id = ($servicePrincipal.AppPrincipalId ); client_secret = $random ; resource = " https://graph.windows.net/" }
24+
25+ # Request an auth token for the service principal from Azure AD Token endpoint
26+ $authResponse = Invoke-RestMethod - Method POST - Uri (" https://login.microsoftonline.com/{0}/oauth2/token" -f $tenantId ) - ContentType " application/x-www-form-urlencoded" - body $authParams
27+
28+ # Extract access token from auth response
29+ $bearerToken = $authResponse.access_token
30+
31+ # Make a Graph query to search for the Application object by appId
32+ $graphResponse = Invoke-RestMethod - Method GET - Uri (" https://graph.windows.net/{0}/applications?api-version=1.6&`$ filter=appId eq `' {1}`' " -f $tenantId , $appId ) - ContentType " application/json" - Headers @ {" Authorization" = ($authResponse.access_token )}
33+
34+ # Get Application's ObjectId
35+ $appObjectId = $graphResponse.value.ObjectId
36+
37+ # Make a Graph query to enable Pre-Consent on the Application object
38+ $graphResponse = Invoke-RestMethod - Method PATCH - Uri (" https://graph.windows.net/{0}/applications/{1}?api-version=1.6" -f $tenantId , $appObjectId ) - ContentType " application/Json" - Headers @ {" Authorization" = ($authResponse.access_token )} - Body ' {"recordConsentConditions":"SilentConsentForPartnerManagedApp"}'
39+
40+ # Delete servicePrincipal object
41+ $servicePrincipal | Remove-MsolServicePrincipal
0 commit comments