-
Notifications
You must be signed in to change notification settings - Fork 160
/
Configure.ps1
227 lines (193 loc) · 10.4 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
[CmdletBinding()]
param(
[PSCredential] $Credential,
[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
)
<#
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.
Before running this script you need to install the AzureAD cmdlets as an administrator.
For this:
1) Run Powershell as an administrator
2) in the PowerShell window, type: Install-Module AzureAD
There are four 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.Open.AzureAD.Model.ResourceAccess
$resourceAccess.Type = $permissionType # Scope = Delegated permissions | Role = Application permissions
$resourceAccess.Id = $exposedPermission.Id # Read directory data
$requiredAccess.ResourceAccess.Add($resourceAccess)
}
}
}
}
#
# Exemple: 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-AzureADServicePrincipal -Filter "DisplayName eq '$applicationDisplayName'"
}
$appid = $sp.AppId
$requiredAccess = New-Object Microsoft.Open.AzureAD.Model.RequiredResourceAccess
$requiredAccess.ResourceAppId = $appid
$requiredAccess.ResourceAccess = New-Object System.Collections.Generic.List[Microsoft.Open.AzureAD.Model.ResourceAccess]
# $sp.Oauth2Permissions | Select Id,AdminConsentDisplayName,Value: To see the list of all the Delegated permissions for the application:
if ($requiredDelegatedPermissions)
{
AddResourcePermission $requiredAccess -exposedPermissions $sp.Oauth2Permissions -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
}
Function UpdateLine([string] $line, [string] $value)
{
$index = $line.IndexOf('=')
$delimiter = ';'
if ($index -eq -1)
{
$index = $line.IndexOf(':')
$delimiter = ','
}
if ($index -ige 0)
{
$line = $line.Substring(0, $index+1) + " "+'"'+$value+'"'+$delimiter
}
return $line
}
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
}
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
Function ConfigureApplications
{
<#.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
#>
# $tenantId is the Active Directory Tenant. This is a GUID which represents the "Directory ID" of the AzureAD tenant
# into which you want to create the apps. Look it up in the Azure portal in the "Properties" of the Azure AD.
# Login to Azure PowerShell (interactive if credentials are not already provided:
# you'll need to sign-in with creds enabling your to create apps in the tenant)
if (!$Credential -and $TenantId)
{
$creds = Connect-AzureAD -TenantId $tenantId
}
else
{
if (!$TenantId)
{
$creds = Connect-AzureAD -Credential $Credential
}
else
{
$creds = Connect-AzureAD -TenantId $tenantId -Credential $Credential
}
}
if (!$tenantId)
{
$tenantId = $creds.Tenant.Id
}
$tenant = Get-AzureADTenantDetail
$tenantName = ($tenant.VerifiedDomains | Where { $_._Default -eq $True }).Name
# Get the user running the script
$user = Get-AzureADUser -ObjectId $creds.Account.Id
# Create the client AAD application
Write-Host "Creating the AAD application (daemon-console)"
$clientAadApplication = New-AzureADApplication -DisplayName "daemon-console" `
-ReplyUrls "https://daemon" `
-IdentifierUris "https://$tenantName/daemon-console" `
-PublicClient $False
# Generate a certificate
Write-Host "Creating the client application (daemon-console)"
$certificate=New-SelfSignedCertificate -Subject CN=DaemonConsoleCert `
-CertStoreLocation "Cert:\CurrentUser\My" `
-KeyExportPolicy Exportable `
-KeySpec Signature
$certKeyId = [Guid]::NewGuid()
$certBase64Value = [System.Convert]::ToBase64String($certificate.GetRawCertData())
$certBase64Thumbprint = [System.Convert]::ToBase64String($certificate.GetCertHash())
# Add a Azure Key Credentials from the certificate for the daemon application
$clientKeyCredentials = New-AzureADApplicationKeyCredential -ObjectId $clientAadApplication.ObjectId `
-CustomKeyIdentifier "CN=DaemonConsoleCert" `
-Type AsymmetricX509Cert `
-Usage Verify `
-Value $certBase64Value `
-StartDate $certificate.NotBefore `
-EndDate $certificate.NotAfter
$currentAppId = $clientAadApplication.AppId
$clientServicePrincipal = New-AzureADServicePrincipal -AppId $currentAppId -Tags {WindowsAzureActiveDirectoryIntegratedApp}
# add the user running the script as an app owner if needed
$owner = Get-AzureADApplicationOwner -ObjectId $clientAadApplication.ObjectId
if ($owner -eq $null)
{
Add-AzureADApplicationOwner -ObjectId $clientAadApplication.ObjectId -RefObjectId $user.ObjectId
Write-Host "'$($user.UserPrincipalName)' added as an application owner to app '$($clientServicePrincipal.DisplayName)'"
}
Write-Host "Done creating the client application (daemon-console)"
# URL of the AAD application in the Azure portal
# Future? $clientPortalUrl = "https://portal.azure.com/#@"+$tenantName+"/blade/Microsoft_AAD_RegisteredApps/ApplicationMenuBlade/Overview/appId/"+$clientAadApplication.AppId+"/objectId/"+$clientAadApplication.ObjectId+"/isMSAApp/"
$clientPortalUrl = "https://portal.azure.com/#blade/Microsoft_AAD_RegisteredApps/ApplicationMenuBlade/CallAnAPI/appId/"+$clientAadApplication.AppId+"/objectId/"+$clientAadApplication.ObjectId+"/isMSAApp/"
Add-Content -Value "<tr><td>client</td><td>$currentAppId</td><td><a href='$clientPortalUrl'>daemon-console</a></td></tr>" -Path createdApps.html
$requiredResourcesAccess = New-Object System.Collections.Generic.List[Microsoft.Open.AzureAD.Model.RequiredResourceAccess]
# Add Required Resources Access (from 'client' to 'Microsoft Graph')
Write-Host "Getting access from 'client' to 'Microsoft Graph'"
$requiredPermissions = GetRequiredPermissions -applicationDisplayName "Microsoft Graph" `
-requiredApplicationPermissions "User.Read.All";
$requiredResourcesAccess.Add($requiredPermissions)
Set-AzureADApplication -ObjectId $clientAadApplication.ObjectId -RequiredResourceAccess $requiredResourcesAccess
Write-Host "Granted permissions."
# Update config file for 'client'
$configFile = $pwd.Path + "\..\daemon-console\appsettings.json"
Write-Host "Updating the sample code ($configFile)"
$dictionary = @{ "Tenant" = $tenantName;"ClientId" = $clientAadApplication.AppId;"ClientSecret" = $clientAppKey;"CertificateName" = "CN=DaemonConsoleCert" };
UpdateTextFile -configFilePath $configFile -dictionary $dictionary
Write-Host ""
Write-Host "IMPORTANT: Think of completing the following manual step(s) in the Azure portal":
Write-Host "- For 'client'"
Write-Host " - Navigate to '$clientPortalUrl'"
Write-Host " - Navigate to the API permissions page and click on 'Grant admin consent for {tenant}'"
Add-Content -Value "</tbody></table></body></html>" -Path createdApps.html
}
# Run interactively (will ask you for the tenant ID)
ConfigureApplications -Credential $Credential -tenantId $TenantId