-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathConfigure.ps1
347 lines (295 loc) · 14.5 KB
/
Configure.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
[CmdletBinding()]
param(
[Parameter(Mandatory=$False, HelpMessage='Tenant ID (This is a GUID which represents the "Directory ID" of the AzureAD tenant into which you want to create the apps')]
[string] $tenantId,
[Parameter(Mandatory=$False, HelpMessage='Azure environment to use while running the script. Default = Global')]
[string] $azureEnvironmentName
)
<#
This script creates the Azure AD applications needed for this sample and updates the configuration files
for the visual Studio projects from the data in the Azure AD applications.
In case you don't have Microsoft.Graph.Applications already installed, the script will automatically install it for the current user
There are two ways to run this script. For more information, read the AppCreationScripts.md file in the same folder as this script.
#>
# Adds the requiredAccesses (expressed as a pipe separated string) to the requiredAccess structure
# The exposed permissions are in the $exposedPermissions collection, and the type of permission (Scope | Role) is
# described in $permissionType
Function AddResourcePermission($requiredAccess, `
$exposedPermissions, [string]$requiredAccesses, [string]$permissionType)
{
foreach($permission in $requiredAccesses.Trim().Split("|"))
{
foreach($exposedPermission in $exposedPermissions)
{
if ($exposedPermission.Value -eq $permission)
{
$resourceAccess = New-Object Microsoft.Graph.PowerShell.Models.MicrosoftGraphResourceAccess
$resourceAccess.Type = $permissionType # Scope = Delegated permissions | Role = Application permissions
$resourceAccess.Id = $exposedPermission.Id # Read directory data
$requiredAccess.ResourceAccess += $resourceAccess
}
}
}
}
#
# Example: GetRequiredPermissions "Microsoft Graph" "Graph.Read|User.Read"
# See also: http://stackoverflow.com/questions/42164581/how-to-configure-a-new-azure-ad-application-through-powershell
Function GetRequiredPermissions([string] $applicationDisplayName, [string] $requiredDelegatedPermissions, [string]$requiredApplicationPermissions, $servicePrincipal)
{
# If we are passed the service principal we use it directly, otherwise we find it from the display name (which might not be unique)
if ($servicePrincipal)
{
$sp = $servicePrincipal
}
else
{
$sp = Get-MgServicePrincipal -Filter "DisplayName eq '$applicationDisplayName'"
}
$appid = $sp.AppId
$requiredAccess = New-Object Microsoft.Graph.PowerShell.Models.MicrosoftGraphRequiredResourceAccess
$requiredAccess.ResourceAppId = $appid
$requiredAccess.ResourceAccess = New-Object System.Collections.Generic.List[Microsoft.Graph.PowerShell.Models.MicrosoftGraphResourceAccess]
# $sp.Oauth2Permissions | Select Id,AdminConsentDisplayName,Value: To see the list of all the Delegated permissions for the application:
if ($requiredDelegatedPermissions)
{
AddResourcePermission $requiredAccess -exposedPermissions $sp.Oauth2PermissionScopes -requiredAccesses $requiredDelegatedPermissions -permissionType "Scope"
}
# $sp.AppRoles | Select Id,AdminConsentDisplayName,Value: To see the list of all the Application permissions for the application
if ($requiredApplicationPermissions)
{
AddResourcePermission $requiredAccess -exposedPermissions $sp.AppRoles -requiredAccesses $requiredApplicationPermissions -permissionType "Role"
}
return $requiredAccess
}
<#.Description
This function takes a string input as a single line, matches a key value and replaces with the replacement value
#>
Function ReplaceInLine([string] $line, [string] $key, [string] $value)
{
$index = $line.IndexOf($key)
if ($index -ige 0)
{
$index2 = $index+$key.Length
$line = $line.Substring(0, $index) + $value + $line.Substring($index2)
}
return $line
}
<#.Description
This function takes a dictionary of keys to search and their replacements and replaces the placeholders in a text file
#>
Function ReplaceInTextFile([string] $configFilePath, [System.Collections.HashTable] $dictionary)
{
$lines = Get-Content $configFilePath
$index = 0
while($index -lt $lines.Length)
{
$line = $lines[$index]
foreach($key in $dictionary.Keys)
{
if ($line.Contains($key))
{
$lines[$index] = ReplaceInLine $line $key $dictionary[$key]
}
}
$index++
}
Set-Content -Path $configFilePath -Value $lines -Force
}
<#.Description
This function creates a new Azure AD scope (OAuth2Permission) with default and provided values
#>
Function CreateScope( [string] $value, [string] $userConsentDisplayName, [string] $userConsentDescription, [string] $adminConsentDisplayName, [string] $adminConsentDescription)
{
$scope = New-Object Microsoft.Graph.PowerShell.Models.MicrosoftGraphPermissionScope
$scope.Id = New-Guid
$scope.Value = $value
$scope.UserConsentDisplayName = $userConsentDisplayName
$scope.UserConsentDescription = $userConsentDescription
$scope.AdminConsentDisplayName = $adminConsentDisplayName
$scope.AdminConsentDescription = $adminConsentDescription
$scope.IsEnabled = $true
$scope.Type = "User"
return $scope
}
<#.Description
This function creates a new Azure AD AppRole with default and provided values
#>
Function CreateAppRole([string] $types, [string] $name, [string] $description)
{
$appRole = New-Object Microsoft.Graph.PowerShell.Models.MicrosoftGraphAppRole
$appRole.AllowedMemberTypes = New-Object System.Collections.Generic.List[string]
$typesArr = $types.Split(',')
foreach($type in $typesArr)
{
$appRole.AllowedMemberTypes += $type;
}
$appRole.DisplayName = $name
$appRole.Id = New-Guid
$appRole.IsEnabled = $true
$appRole.Description = $description
$appRole.Value = $name;
return $appRole
}
<#.Description
This function takes a string input as a single line, matches a key value and replaces with the replacement value
#>
Function UpdateLine([string] $line, [string] $value)
{
$index = $line.IndexOf(':')
$lineEnd = ''
if($line[$line.Length - 1] -eq ','){ $lineEnd = ',' }
if ($index -ige 0)
{
$line = $line.Substring(0, $index+1) + " " + '"' + $value+ '"' + $lineEnd
}
return $line
}
<#.Description
This function takes a dictionary of keys to search and their replacements and replaces the placeholders in a text file
#>
Function UpdateTextFile([string] $configFilePath, [System.Collections.HashTable] $dictionary)
{
$lines = Get-Content $configFilePath
$index = 0
while($index -lt $lines.Length)
{
$line = $lines[$index]
foreach($key in $dictionary.Keys)
{
if ($line.Contains($key))
{
$lines[$index] = UpdateLine $line $dictionary[$key]
}
}
$index++
}
Set-Content -Path $configFilePath -Value $lines -Force
}
<#.Description
This function takes a string as input and creates an instance of an Optional claim object
#>
Function CreateOptionalClaim([string] $name)
{
<#.Description
This function creates a new Azure AD optional claims with default and provided values
#>
$appClaim = New-Object Microsoft.Graph.PowerShell.Models.MicrosoftGraphOptionalClaim
$appClaim.AdditionalProperties = New-Object System.Collections.Generic.List[string]
$appClaim.Source = $null
$appClaim.Essential = $false
$appClaim.Name = $name
return $appClaim
}
<#.Description
Primary entry method to create and configure app registrations
#>
Function ConfigureApplications
{
$isOpenSSl = 'N' #temporary disable open certificate creation
<#.Description
This function creates the Azure AD applications for the sample in the provided Azure AD tenant and updates the
configuration files in the client and service project of the visual studio solution (App.Config and Web.Config)
so that they are consistent with the Applications parameters
#>
if (!$azureEnvironmentName)
{
$azureEnvironmentName = "Global"
}
# Connect to the Microsoft Graph API, non-interactive is not supported for the moment (Oct 2021)
Write-Host "Connecting to Microsoft Graph"
if ($tenantId -eq "") {
Connect-MgGraph -Scopes "Application.ReadWrite.All" -Environment $azureEnvironmentName
$tenantId = (Get-MgContext).TenantId
}
else {
Connect-MgGraph -TenantId $tenantId -Scopes "Application.ReadWrite.All" -Environment $azureEnvironmentName
}
# Create the client AAD application
Write-Host "Creating the AAD application (msal-node-desktop)"
# create the application
$clientAadApplication = New-MgApplication -DisplayName "msal-node-desktop" `
-PublicClient `
@{ `
RedirectUris = "http://localhost"; `
} `
-SignInAudience AzureADMyOrg `
#end of command
$currentAppId = $clientAadApplication.AppId
$currentAppObjectId = $clientAadApplication.Id
# create the service principal of the newly created application
$clientServicePrincipal = New-MgServicePrincipal -AppId $currentAppId -Tags {WindowsAzureActiveDirectoryIntegratedApp}
# add the user running the script as an app owner if needed
$owner = Get-MgApplicationOwner -ApplicationId $currentAppObjectId
if ($owner -eq $null)
{
New-MgApplicationOwnerByRef -ApplicationId $currentAppObjectId -BodyParameter = @{"@odata.id" = "htps://graph.microsoft.com/v1.0/directoryObjects/$user.ObjectId"}
Write-Host "'$($user.UserPrincipalName)' added as an application owner to app '$($clientServicePrincipal.DisplayName)'"
}
# Add Claims
$optionalClaims = New-Object Microsoft.Graph.PowerShell.Models.MicrosoftGraphOptionalClaims
$optionalClaims.AccessToken = New-Object System.Collections.Generic.List[Microsoft.Graph.PowerShell.Models.MicrosoftGraphOptionalClaim]
$optionalClaims.IdToken = New-Object System.Collections.Generic.List[Microsoft.Graph.PowerShell.Models.MicrosoftGraphOptionalClaim]
$optionalClaims.Saml2Token = New-Object System.Collections.Generic.List[Microsoft.Graph.PowerShell.Models.MicrosoftGraphOptionalClaim]
# Add Optional Claims
$newClaim = CreateOptionalClaim -name "login_hint"
$optionalClaims.IdToken += ($newClaim)
Update-MgApplication -ApplicationId $currentAppObjectId -OptionalClaims $optionalClaims
Write-Host "Done creating the client application (msal-node-desktop)"
# URL of the AAD application in the Azure portal
# Future? $clientPortalUrl = "https://portal.azure.com/#@"+$tenantName+"/blade/Microsoft_AAD_RegisteredApps/ApplicationMenuBlade/Overview/appId/"+$currentAppId+"/objectId/"+$currentAppObjectId+"/isMSAApp/"
$clientPortalUrl = "https://portal.azure.com/#blade/Microsoft_AAD_RegisteredApps/ApplicationMenuBlade/CallAnAPI/appId/"+$currentAppId+"/objectId/"+$currentAppObjectId+"/isMSAApp/"
Add-Content -Value "<tr><td>client</td><td>$currentAppId</td><td><a href='$clientPortalUrl'>msal-node-desktop</a></td></tr>" -Path createdApps.html
# Declare a list to hold RRA items
$requiredResourcesAccess = New-Object System.Collections.Generic.List[Microsoft.Graph.PowerShell.Models.MicrosoftGraphRequiredResourceAccess]
# Add Required Resources Access (from 'client' to 'Microsoft Graph')
Write-Host "Getting access from 'client' to 'Microsoft Graph'"
$requiredPermission = GetRequiredPermissions -applicationDisplayName "Microsoft Graph"`
-requiredDelegatedPermissions "User.Read"
$requiredResourcesAccess.Add($requiredPermission)
Write-Host "Added 'Microsoft Graph' to the RRA list."
# Useful for RRA additions troubleshooting
# $requiredResourcesAccess.Count
# $requiredResourcesAccess
Update-MgApplication -ApplicationId $currentAppObjectId -RequiredResourceAccess $requiredResourcesAccess
Write-Host "Granted permissions."
# print the registered app portal URL for any further navigation
Write-Host "Successfully registered and configured that app registration for 'msal-node-desktop' at `n $clientPortalUrl" -ForegroundColor Green
# Update config file for 'client'
# $configFile = $pwd.Path + "\..\App\authConfig.js"
$configFile = $(Resolve-Path ($pwd.Path + "\..\App\authConfig.js"))
$dictionary = @{ "Enter_the_Tenant_Info_Here" = $tenantId;"Enter_the_Application_Id_Here" = $clientAadApplication.AppId;"Enter_the_Cloud_Instance_Id_Here" = 'https://login.microsoftonline.com/';"Enter_the_Graph_Endpoint_Here" = 'https://graph.microsoft.com/' };
Write-Host "Updating the sample config '$configFile' with the following config values:" -ForegroundColor Yellow
$dictionary
Write-Host "-----------------"
ReplaceInTextFile -configFilePath $configFile -dictionary $dictionary
if($isOpenSSL -eq 'Y')
{
Write-Host -ForegroundColor Green "------------------------------------------------------------------------------------------------"
Write-Host "You have generated certificate using OpenSSL so follow below steps: "
Write-Host "Install the certificate on your system from current folder."
Write-Host -ForegroundColor Green "------------------------------------------------------------------------------------------------"
}
Add-Content -Value "</tbody></table></body></html>" -Path createdApps.html
} # end of ConfigureApplications function
# Pre-requisites
if ($null -eq (Get-Module -ListAvailable -Name "Microsoft.Graph.Applications")) {
Install-Module "Microsoft.Graph.Applications" -Scope CurrentUser
}
Import-Module Microsoft.Graph.Applications
Set-Content -Value "<html><body><table>" -Path createdApps.html
Add-Content -Value "<thead><tr><th>Application</th><th>AppId</th><th>Url in the Azure portal</th></tr></thead><tbody>" -Path createdApps.html
$ErrorActionPreference = "Stop"
# Run interactively (will ask you for the tenant ID)
try
{
ConfigureApplications -tenantId $tenantId -environment $azureEnvironmentName
}
catch
{
$_.Exception.ToString() | out-host
$message = $_
Write-Warning $Error[0]
Write-Host "Unable to register apps. Error is $message." -ForegroundColor White -BackgroundColor Red
}
Write-Host "Disconnecting from tenant"
Disconnect-MgGraph