Skip to content
This repository was archived by the owner on May 17, 2024. It is now read-only.

Commit db017f2

Browse files
Minor nits and bits
1 parent 43eb197 commit db017f2

File tree

7 files changed

+180
-105
lines changed

7 files changed

+180
-105
lines changed

5-AccessControl/1-call-api-roles/API/TodoListAPI/Startup.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ public void ConfigureServices(IServiceCollection services)
5151

5252
options.Events.OnTokenValidated = async context =>
5353
{
54-
string[] allowedClientApps = { Configuration["AzureAd:ClientId"] }; // In this scenario, client and service share the same clientId
54+
string[] allowedClientApps = { Configuration["AzureAd:ClientId"] }; // In this scenario, client and service share the same clientId and this app's API only allows call from its own SPA
5555

5656
string clientappId = context?.Principal?.Claims
5757
.FirstOrDefault(x => x.Type == "azp" || x.Type == "appid")?.Value;

5-AccessControl/1-call-api-roles/AppCreationScripts/Cleanup.ps1

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ param(
77
[string] $azureEnvironmentName
88
)
99

10+
1011
Function Cleanup
1112
{
1213
if (!$azureEnvironmentName)
@@ -24,11 +25,13 @@ Function Cleanup
2425

2526
# Connect to the Microsoft Graph API
2627
Write-Host "Connecting to Microsoft Graph"
27-
if ($tenantId -eq "") {
28+
if ($tenantId -eq "")
29+
{
2830
Connect-MgGraph -Scopes "Application.ReadWrite.All" -Environment $azureEnvironmentName
2931
$tenantId = (Get-MgContext).TenantId
3032
}
31-
else {
33+
else
34+
{
3235
Connect-MgGraph -TenantId $tenantId -Scopes "Application.ReadWrite.All" -Environment $azureEnvironmentName
3336
}
3437

@@ -81,7 +84,17 @@ Import-Module Microsoft.Graph.Applications
8184
$ErrorActionPreference = "Stop"
8285

8386

84-
Cleanup -tenantId $tenantId -environment $azureEnvironmentName
87+
try
88+
{
89+
Cleanup -tenantId $tenantId -environment $azureEnvironmentName
90+
}
91+
catch
92+
{
93+
$_.Exception.ToString() | out-host
94+
$message = $_
95+
Write-Warning $Error[0]
96+
Write-Host "Unable to register apps. Error is $message." -ForegroundColor White -BackgroundColor Red
97+
}
8598

8699
Write-Host "Disconnecting from tenant"
87100
Disconnect-MgGraph

5-AccessControl/1-call-api-roles/AppCreationScripts/CleanupUsersAndAssignRoles.ps1

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -49,10 +49,16 @@ Function CleanupRolesUsersAndRoleAssignments
4949
}
5050
else
5151
{
52-
Write-Host "couldn't find application (msal-angular-app)" -BackgroundColor Red
52+
Write-Host "Couldn't find application (msal-angular-app)" -BackgroundColor Red
5353
}
5454
}
5555

56+
if ($null -eq (Get-Module -ListAvailable -Name "Microsoft.Graph.Authentication")) {
57+
Install-Module "Microsoft.Graph.Authentication" -Scope CurrentUser
58+
}
59+
60+
Import-Module Microsoft.Graph.Authentication
61+
5662
if ($null -eq (Get-Module -ListAvailable -Name "Microsoft.Graph.Applications")) {
5763
Install-Module "Microsoft.Graph.Applications" -Scope CurrentUser
5864
}
@@ -65,14 +71,17 @@ if ($null -eq (Get-Module -ListAvailable -Name "Microsoft.Graph.Users")) {
6571

6672
Import-Module Microsoft.Graph.Users
6773

68-
# Run interactively (will ask you for the tenant ID)
69-
70-
try {
74+
try
75+
{
76+
# Run interactively (will ask you for the tenant ID)
7177
CleanupRolesUsersAndRoleAssignments -tenantId $tenantId -environment $azureEnvironmentName
72-
} catch {
78+
}
79+
catch
80+
{
81+
$_.Exception.ToString() | out-host
7382
$message = $_
74-
Write-Warning $Error[0]
75-
Write-Host "Unable to register apps. Error is $message." -ForegroundColor White -BackgroundColor Red
83+
Write-Warning $Error[0]
84+
Write-Host "Unable to cleanup app roles and assignments. Error is $message." -ForegroundColor White -BackgroundColor Red
7685
}
7786

7887
Write-Host "Disconnecting from tenant"

5-AccessControl/1-call-api-roles/AppCreationScripts/Configure.ps1

Lines changed: 92 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ param(
1313
1414
In case you don't have Microsoft.Graph.Applications already installed, the script will automatically install it for the current user
1515
16-
There are four ways to run this script. For more information, read the AppCreationScripts.md file in the same folder as this script.
16+
There are two ways to run this script. For more information, read the AppCreationScripts.md file in the same folder as this script.
1717
#>
1818

1919
# Adds the requiredAccesses (expressed as a pipe separated string) to the requiredAccess structure
@@ -71,6 +71,9 @@ Function GetRequiredPermissions([string] $applicationDisplayName, [string] $requ
7171
}
7272

7373

74+
<#.Description
75+
This function takes a string input as a single line, matches a key value and replaces with the replacement value
76+
#>
7477
Function ReplaceInLine([string] $line, [string] $key, [string] $value)
7578
{
7679
$index = $line.IndexOf($key)
@@ -82,6 +85,9 @@ Function ReplaceInLine([string] $line, [string] $key, [string] $value)
8285
return $line
8386
}
8487

88+
<#.Description
89+
This function takes a dictionary of keys to search and their replacements and replaces the placeholders in a text file
90+
#>
8591
Function ReplaceInTextFile([string] $configFilePath, [System.Collections.HashTable] $dictionary)
8692
{
8793
$lines = Get-Content $configFilePath
@@ -101,6 +107,7 @@ Function ReplaceInTextFile([string] $configFilePath, [System.Collections.HashTab
101107

102108
Set-Content -Path $configFilePath -Value $lines -Force
103109
}
110+
104111
<#.Description
105112
This function creates a new Azure AD scope (OAuth2Permission) with default and provided values
106113
#>
@@ -137,6 +144,49 @@ Function CreateAppRole([string] $types, [string] $name, [string] $description)
137144
$appRole.Value = $name;
138145
return $appRole
139146
}
147+
<#.Description
148+
This function takes a string input as a single line, matches a key value and replaces with the replacement value
149+
#>
150+
Function UpdateLine([string] $line, [string] $value)
151+
{
152+
$index = $line.IndexOf(':')
153+
$lineEnd = ''
154+
155+
if($line[$line.Length - 1] -eq ','){ $lineEnd = ',' }
156+
157+
if ($index -ige 0)
158+
{
159+
$line = $line.Substring(0, $index+1) + " " + '"' + $value+ '"' + $lineEnd
160+
}
161+
return $line
162+
}
163+
164+
<#.Description
165+
This function takes a dictionary of keys to search and their replacements and replaces the placeholders in a text file
166+
#>
167+
Function UpdateTextFile([string] $configFilePath, [System.Collections.HashTable] $dictionary)
168+
{
169+
$lines = Get-Content $configFilePath
170+
$index = 0
171+
while($index -lt $lines.Length)
172+
{
173+
$line = $lines[$index]
174+
foreach($key in $dictionary.Keys)
175+
{
176+
if ($line.Contains($key))
177+
{
178+
$lines[$index] = UpdateLine $line $dictionary[$key]
179+
}
180+
}
181+
$index++
182+
}
183+
184+
Set-Content -Path $configFilePath -Value $lines -Force
185+
}
186+
187+
<#.Description
188+
This function takes a string as input and creates an instance of an Optional claim object
189+
#>
140190
Function CreateOptionalClaim([string] $name)
141191
{
142192
<#.Description
@@ -151,6 +201,9 @@ Function CreateOptionalClaim([string] $name)
151201
return $appClaim
152202
}
153203

204+
<#.Description
205+
Primary entry method to create and configure app registrations
206+
#>
154207
Function ConfigureApplications
155208
{
156209
$isOpenSSl = 'N' #temporary disable open certificate creation
@@ -192,8 +245,10 @@ Function ConfigureApplications
192245
} `
193246
-SignInAudience AzureADMyOrg `
194247
#end of command
248+
195249
$clientIdentifierUri = 'api://'+$clientAadApplication.AppId
196250
Update-MgApplication -ApplicationId $clientAadApplication.Id -IdentifierUris @($clientIdentifierUri)
251+
197252

198253
# create the service principal of the newly created application
199254
$currentAppId = $clientAadApplication.AppId
@@ -214,14 +269,13 @@ Function ConfigureApplications
214269
$optionalClaims.IdToken = New-Object System.Collections.Generic.List[Microsoft.Graph.PowerShell.Models.MicrosoftGraphOptionalClaim]
215270
$optionalClaims.Saml2Token = New-Object System.Collections.Generic.List[Microsoft.Graph.PowerShell.Models.MicrosoftGraphOptionalClaim]
216271

217-
218272
# Add Optional Claims
219273

220274
$newClaim = CreateOptionalClaim -name "acct"
221275
$optionalClaims.IdToken += ($newClaim)
222276
Update-MgApplication -ApplicationId $clientAadApplication.Id -OptionalClaims $optionalClaims
223277

224-
# Add application Roles
278+
# Add application Roles for users and groups
225279
$appRoles = New-Object System.Collections.Generic.List[Microsoft.Graph.PowerShell.Models.MicrosoftGraphAppRole]
226280
$newRole = CreateAppRole -types "User" -name "TaskAdmin" -description "Admins can read any user's todo list"
227281
$appRoles.Add($newRole)
@@ -232,6 +286,7 @@ Function ConfigureApplications
232286
# rename the user_impersonation scope if it exists to match the readme steps or add a new scope
233287

234288
# delete default scope i.e. User_impersonation
289+
# Alex: the scope deletion doesn't work - see open issue - https://github.com/microsoftgraph/msgraph-sdk-powershell/issues/1054
235290
$scopes = New-Object System.Collections.Generic.List[Microsoft.Graph.PowerShell.Models.MicrosoftGraphPermissionScope]
236291
$scope = $clientAadApplication.Api.Oauth2PermissionScopes | Where-Object { $_.Value -eq "User_impersonation" }
237292

@@ -248,10 +303,10 @@ Function ConfigureApplications
248303

249304
$scopes = New-Object System.Collections.Generic.List[Microsoft.Graph.PowerShell.Models.MicrosoftGraphPermissionScope]
250305
$scope = CreateScope -value access_via_approle_assignments `
251-
-userConsentDisplayName "Access msal-angular-app" `
252-
-userConsentDescription "Allow the application to access msal-angular-app on your behalf." `
253-
-adminConsentDisplayName "Access msal-angular-app" `
254-
-adminConsentDescription "Allows the app to have the same access to information in the directory on behalf of an admin."
306+
-userConsentDisplayName "Access 'msal-angular-app' as the signed-in user assigned to App role" `
307+
-userConsentDescription "Allow the app to access the 'msal-angular-app' on your behalf after assignment to one or more App roles" `
308+
-adminConsentDisplayName "Access 'msal-angular-app' as the signed-in user assigned to App role" `
309+
-adminConsentDescription "Allow the app to access the 'msal-angular-app' as a signed-in user assigned to one or more App roles"
255310

256311
$scopes.Add($scope)
257312

@@ -262,73 +317,50 @@ Function ConfigureApplications
262317
# URL of the AAD application in the Azure portal
263318
# Future? $clientPortalUrl = "https://portal.azure.com/#@"+$tenantName+"/blade/Microsoft_AAD_RegisteredApps/ApplicationMenuBlade/Overview/appId/"+$clientAadApplication.AppId+"/objectId/"+$clientAadApplication.Id+"/isMSAApp/"
264319
$clientPortalUrl = "https://portal.azure.com/#blade/Microsoft_AAD_RegisteredApps/ApplicationMenuBlade/CallAnAPI/appId/"+$clientAadApplication.AppId+"/objectId/"+$clientAadApplication.Id+"/isMSAApp/"
320+
265321
Add-Content -Value "<tr><td>client</td><td>$currentAppId</td><td><a href='$clientPortalUrl'>msal-angular-app</a></td></tr>" -Path createdApps.html
322+
# Declare a list to hold RRA items
266323
$requiredResourcesAccess = New-Object System.Collections.Generic.List[Microsoft.Graph.PowerShell.Models.MicrosoftGraphRequiredResourceAccess]
267-
324+
268325
# Add Required Resources Access (from 'client' to 'client')
269326
Write-Host "Getting access from 'client' to 'client'"
270-
$requiredPermission = GetRequiredPermissions -applicationDisplayName "msal-angular-app" `
271-
-requiredDelegatedPermissions "access_via_approle_assignments" `
327+
$requiredPermission = GetRequiredPermissions -applicationDisplayName "msal-angular-app"`
328+
-requiredDelegatedPermissions "access_via_approle_assignments"
272329

273330
$requiredResourcesAccess.Add($requiredPermission)
331+
Write-Host "Added 'client' to the RRA list."
332+
# Useful for RRA additions troubleshooting
333+
# $requiredResourcesAccess.Count
334+
# $requiredResourcesAccess
335+
274336
Update-MgApplication -ApplicationId $clientAadApplication.Id -RequiredResourceAccess $requiredResourcesAccess
275-
Write-Host "Granted permissions."
276-
277-
Write-Host "Successfully registered and configured that app registration for 'msal-angular-app' at" -ForegroundColor Green
278-
279-
# print the registered app portal URL for any further navigation
280-
$clientPortalUrl
281-
Function UpdateLine([string] $line, [string] $value)
282-
{
283-
$index = $line.IndexOf(':')
284-
$lineEnd = ''
285-
286-
if($line[$line.Length - 1] -eq ','){ $lineEnd = ',' }
337+
Write-Host "Granted permissions."
287338

288-
if ($index -ige 0)
289-
{
290-
$line = $line.Substring(0, $index+1) + " " + '"' + $value+ '"' + $lineEnd
291-
}
292-
return $line
293-
}
294339

295-
Function UpdateTextFile([string] $configFilePath, [System.Collections.HashTable] $dictionary)
296-
{
297-
$lines = Get-Content $configFilePath
298-
$index = 0
299-
while($index -lt $lines.Length)
300-
{
301-
$line = $lines[$index]
302-
foreach($key in $dictionary.Keys)
303-
{
304-
if ($line.Contains($key))
305-
{
306-
$lines[$index] = UpdateLine $line $dictionary[$key]
307-
}
308-
}
309-
$index++
310-
}
311-
312-
Set-Content -Path $configFilePath -Value $lines -Force
313-
}
340+
# print the registered app portal URL for any further navigation
341+
Write-Host "Successfully registered and configured that app registration for 'msal-angular-app' at `n $clientPortalUrl" -ForegroundColor Red
314342

315343
# Update config file for 'client'
344+
# $configFile = $pwd.Path + "\..\API\TodoListAPI\appsettings.json"
316345
$configFile = $(Resolve-Path ($pwd.Path + "\..\API\TodoListAPI\appsettings.json"))
317346

318347
$dictionary = @{ "Enter the ID of your Azure AD tenant copied from the Azure portal" = $tenantId;"Enter the application ID (clientId) of the 'TodoListAPI' application copied from the Azure portal" = $clientAadApplication.AppId };
319348

320-
Write-Host "Updating the sample config '$configFile' with the following config values:"
349+
Write-Host "Updating the sample config '$configFile' with the following config values:" -ForegroundColor Green
321350
$dictionary
351+
Write-Host "-----------------"
322352

323353
ReplaceInTextFile -configFilePath $configFile -dictionary $dictionary
324354

325355
# Update config file for 'client'
356+
# $configFile = $pwd.Path + "\..\SPA\src\app\auth-config.ts"
326357
$configFile = $(Resolve-Path ($pwd.Path + "\..\SPA\src\app\auth-config.ts"))
327358

328359
$dictionary = @{ "Enter_the_Application_Id_Here" = $clientAadApplication.AppId;"Enter_the_Tenant_Info_Here" = $tenantId;"Enter_the_Web_Api_Application_Id_Here" = $clientAadApplication.AppId };
329360

330-
Write-Host "Updating the sample config '$configFile' with the following config values:"
361+
Write-Host "Updating the sample config '$configFile' with the following config values:" -ForegroundColor Green
331362
$dictionary
363+
Write-Host "-----------------"
332364

333365
ReplaceInTextFile -configFilePath $configFile -dictionary $dictionary
334366
Write-Host -ForegroundColor Green "------------------------------------------------------------------------------------------------"
@@ -339,14 +371,15 @@ Function UpdateTextFile([string] $configFilePath, [System.Collections.HashTable]
339371
Write-Host " - Or you can run the .\CreateUsersAndAssignRoles.ps1 command to automatically create a number of users, and assign these users to the app roles of this app." -ForegroundColor Red
340372
Write-Host " - Application 'client' publishes app roles . Do remember to navigate to the app registration in the app portal and assign users to these app roles" -ForegroundColor Red
341373
Write-Host -ForegroundColor Green "------------------------------------------------------------------------------------------------"
342-
if($isOpenSSL -eq 'Y')
343-
{
344-
Write-Host -ForegroundColor Green "------------------------------------------------------------------------------------------------"
345-
Write-Host "You have generated certificate using OpenSSL so follow below steps: "
346-
Write-Host "Install the certificate on your system from current folder."
347-
Write-Host -ForegroundColor Green "------------------------------------------------------------------------------------------------"
348-
}
349-
Add-Content -Value "</tbody></table></body></html>" -Path createdApps.html
374+
375+
if($isOpenSSL -eq 'Y')
376+
{
377+
Write-Host -ForegroundColor Green "------------------------------------------------------------------------------------------------"
378+
Write-Host "You have generated certificate using OpenSSL so follow below steps: "
379+
Write-Host "Install the certificate on your system from current folder."
380+
Write-Host -ForegroundColor Green "------------------------------------------------------------------------------------------------"
381+
}
382+
Add-Content -Value "</tbody></table></body></html>" -Path createdApps.html
350383
} # end of ConfigureApplications function
351384

352385
# Pre-requisites
@@ -369,8 +402,9 @@ try
369402
}
370403
catch
371404
{
405+
$_.Exception.ToString() | out-host
372406
$message = $_
373-
Write-Warning $Error[0]
407+
Write-Warning $Error[0]
374408
Write-Host "Unable to register apps. Error is $message." -ForegroundColor White -BackgroundColor Red
375409
}
376410
Write-Host "Disconnecting from tenant"

0 commit comments

Comments
 (0)