Skip to content

Commit a142345

Browse files
author
Kalyan Krishna
committed
roles sample upgraded
1 parent 45d5bd9 commit a142345

File tree

11 files changed

+553
-63
lines changed

11 files changed

+553
-63
lines changed

5-WebApp-AuthZ/5-1-Roles/AppCreationScripts/AppCreationScripts.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Registering the Azure Active Directory applications and updating the configuration files for this sample using PowerShell scripts
1+
# Registering the sample apps with Microsoft Identity Platform and updating the configuration files using PowerShell scripts
22

33
## Overview
44

@@ -9,7 +9,7 @@
99
```PowerShell
1010
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process -Force
1111
```
12-
1. Run the script to create your Azure AD application and configure the code of the sample application accordinly. (Other ways of running the scripts are described below)
12+
1. Run the script to create your Azure AD application and configure the code of the sample application accordingly. (Other ways of running the scripts are described below)
1313
```PowerShell
1414
.\AppCreationScripts\Configure.ps1
1515
```

5-WebApp-AuthZ/5-1-Roles/AppCreationScripts/Cleanup.ps1

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,11 @@ param(
55
[string] $tenantId
66
)
77

8-
if ((Get-Module -ListAvailable -Name "AzureAD") -eq $null) {
8+
if ($null -eq (Get-Module -ListAvailable -Name "AzureAD")) {
99
Install-Module "AzureAD" -Scope CurrentUser
1010
}
1111
Import-Module AzureAD
12-
$ErrorActionPreference = 'Stop'
12+
$ErrorActionPreference = "Stop"
1313

1414
Function Cleanup
1515
{
@@ -44,19 +44,27 @@ This function removes the Azure AD applications for the sample. These applicatio
4444
$tenantId = $creds.Tenant.Id
4545
}
4646
$tenant = Get-AzureADTenantDetail
47-
$tenantName = ($tenant.VerifiedDomains | Where { $_._Default -eq $True }).Name
47+
$tenantName = ($tenant.VerifiedDomains | Where-Object { $_._Default -eq $True }).Name
4848

4949
# Removes the applications
5050
Write-Host "Cleaning-up applications from tenant '$tenantName'"
5151

5252
Write-Host "Removing 'webApp' (WebApp-RolesClaims) if needed"
53-
$app=Get-AzureADApplication -Filter "DisplayName eq 'WebApp-RolesClaims'"
53+
Get-AzureADApplication -Filter "DisplayName eq 'WebApp-RolesClaims'" | ForEach-Object {Remove-AzureADApplication -ObjectId $_.ObjectId }
54+
$apps = Get-AzureADApplication -Filter "DisplayName eq 'WebApp-RolesClaims'"
55+
if ($apps)
56+
{
57+
Remove-AzureADApplication -ObjectId $apps.ObjectId
58+
}
5459

55-
if ($app)
60+
foreach ($app in $apps)
5661
{
5762
Remove-AzureADApplication -ObjectId $app.ObjectId
58-
Write-Host "Removed WebApp-RolesClaims."
59-
}
63+
Write-Host "Removed WebApp-RolesClaims.."
6064
}
65+
# also remove service principals of this app
66+
Get-AzureADServicePrincipal -filter "DisplayName eq 'WebApp-RolesClaims'" | ForEach-Object {Remove-AzureADServicePrincipal -ObjectId $_.Id -Confirm:$false}
67+
68+
}
6169

62-
Cleanup -Credential $Credential -tenantId $TenantId
70+
Cleanup -Credential $Credential -tenantId $TenantId

5-WebApp-AuthZ/5-1-Roles/AppCreationScripts/Configure.ps1

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ Function AddResourcePermission($requiredAccess, `
6565
}
6666

6767
#
68-
# Exemple: GetRequiredPermissions "Microsoft Graph" "Graph.Read|User.Read"
68+
# Example: GetRequiredPermissions "Microsoft Graph" "Graph.Read|User.Read"
6969
# See also: http://stackoverflow.com/questions/42164581/how-to-configure-a-new-azure-ad-application-through-powershell
7070
Function GetRequiredPermissions([string] $applicationDisplayName, [string] $requiredDelegatedPermissions, [string]$requiredApplicationPermissions, $servicePrincipal)
7171
{
@@ -137,14 +137,15 @@ Function UpdateTextFile([string] $configFilePath, [System.Collections.HashTable]
137137
Set-Content -Value "<html><body><table>" -Path createdApps.html
138138
Add-Content -Value "<thead><tr><th>Application</th><th>AppId</th><th>Url in the Azure portal</th></tr></thead><tbody>" -Path createdApps.html
139139

140+
$ErrorActionPreference = "Stop"
141+
140142
Function ConfigureApplications
141143
{
142144
<#.Description
143145
This function creates the Azure AD applications for the sample in the provided Azure AD tenant and updates the
144146
configuration files in the client and service project of the visual studio solution (App.Config and Web.Config)
145147
so that they are consistent with the Applications parameters
146148
#>
147-
148149
$commonendpoint = "common"
149150

150151
# $tenantId is the Active Directory Tenant. This is a GUID which represents the "Directory ID" of the AzureAD tenant
@@ -176,7 +177,7 @@ Function ConfigureApplications
176177
$tenant = Get-AzureADTenantDetail
177178
$tenantName = ($tenant.VerifiedDomains | Where { $_._Default -eq $True }).Name
178179

179-
# Get the user running the script
180+
# Get the user running the script to add the user as the app owner
180181
$user = Get-AzureADUser -ObjectId $creds.Account.Id
181182

182183
# Create the webApp AAD application
@@ -186,6 +187,7 @@ Function ConfigureApplications
186187
$fromDate = [DateTime]::Now;
187188
$key = CreateAppKey -fromDate $fromDate -durationInYears 2 -pw $pw
188189
$webAppAppKey = $pw
190+
# create the application
189191
$webAppAadApplication = New-AzureADApplication -DisplayName "WebApp-RolesClaims" `
190192
-HomePage "https://localhost:44321/" `
191193
-LogoutUrl "https://localhost:44321/signout-oidc" `
@@ -195,6 +197,7 @@ Function ConfigureApplications
195197
-Oauth2AllowImplicitFlow $true `
196198
-PublicClient $False
197199

200+
# create the service principal of the newly created application
198201
$currentAppId = $webAppAadApplication.AppId
199202
$webAppServicePrincipal = New-AzureADServicePrincipal -AppId $currentAppId -Tags {WindowsAzureActiveDirectoryIntegratedApp} -AppRoleAssignmentRequired $true
200203

@@ -209,6 +212,7 @@ Function ConfigureApplications
209212
New-AzureADUserAppRoleAssignment -ObjectId $user.ObjectId -PrincipalId $user.ObjectId -ResourceId $webAppServicePrincipal.ObjectId -Id ([Guid]::Empty)
210213
}
211214

215+
212216
Write-Host "Done creating the webApp application (WebApp-RolesClaims)"
213217

214218
# URL of the AAD application in the Azure portal
@@ -249,7 +253,8 @@ Function ConfigureApplications
249253
# Pre-requisites
250254
if ((Get-Module -ListAvailable -Name "AzureAD") -eq $null) {
251255
Install-Module "AzureAD" -Scope CurrentUser
252-
}
256+
}
257+
253258
Import-Module AzureAD
254259

255260
# Run interactively (will ask you for the tenant ID)

5-WebApp-AuthZ/5-1-Roles/AppCreationScripts/CreateUsersAndRoles.ps1

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -107,10 +107,11 @@ Function CreateRolesUsersAndRoleAssignments
107107
$servicePrincipal = Get-AzureADServicePrincipal -Filter "AppId eq '$($app.AppId)'"
108108

109109
Set-AzureADApplication -ObjectId $app.ObjectId -AppRoles $appRoles
110-
Write-Host "Successfully added app roles to the app 'WebApp-RolesClaims'."
111110

112111
$appName = $app.DisplayName
113112

113+
Write-Host "Successfully added app roles to the app '$appName'."
114+
114115
Write-Host "Creating users and assigning them to roles."
115116

116117
# Create users
@@ -120,19 +121,19 @@ Function CreateRolesUsersAndRoleAssignments
120121
$userAssignment = New-AzureADUserAppRoleAssignment -ObjectId $user.ObjectId -PrincipalId $user.ObjectId -ResourceId $servicePrincipal.ObjectId -Id $directoryViewerRole.Id
121122

122123
# Creating a directory viewer
123-
Write-Host "Creating a user and assigning to '$($directoryViewerRole.DisplayName)' role"
124+
Write-Host "Creating a new user and assigning to '$($directoryViewerRole.DisplayName)' role"
124125
$aDirectoryViewer = CreateUserRepresentingAppRole $appName $directoryViewerRole $tenantName
125126
$userAssignment = New-AzureADUserAppRoleAssignment -ObjectId $aDirectoryViewer.ObjectId -PrincipalId $aDirectoryViewer.ObjectId -ResourceId $servicePrincipal.ObjectId -Id $directoryViewerRole.Id
126-
Write-Host "Created "($anApprover.UserPrincipalName)" with password 'test123456789.'"
127+
Write-Host "Created user "($aDirectoryViewer.UserPrincipalName)" with password 'test123456789.'"
127128

128129
# Creating a users reader
129130
Write-Host "Creating a user and assigning to '$($userreaderRole.DisplayName)' role"
130-
$auserreaderRole = CreateUserRepresentingAppRole $appName $userreaderRole $tenantName
131-
$userAssignment = New-AzureADUserAppRoleAssignment -ObjectId $auserreaderRole.ObjectId -PrincipalId $auserreaderRole.ObjectId -ResourceId $servicePrincipal.ObjectId -Id $userreaderRole.Id
132-
Write-Host "Created "($auserreaderRole.UserPrincipalName)" with password 'test123456789.'"
131+
$auserreader = CreateUserRepresentingAppRole $appName $userreaderRole $tenantName
132+
$userAssignment = New-AzureADUserAppRoleAssignment -ObjectId $auserreader.ObjectId -PrincipalId $auserreader.ObjectId -ResourceId $servicePrincipal.ObjectId -Id $userreaderRole.Id
133+
Write-Host "Created user "($auserreader.UserPrincipalName)" with password 'test123456789.'"
133134
}
134135
else {
135-
Write-Host "Failed to add app roles to the app 'WebApp-RolesClaims'."
136+
Write-Host -ForegroundColor Red "Failed to add app roles to the app 'WebApp-RolesClaims'."
136137
}
137138

138139
Write-Host -ForegroundColor Green "Run the ..\CleanupUsersAndRoles.ps1 command to remove users created for this sample's application ."

5-WebApp-AuthZ/5-1-Roles/Controllers/HomeController.cs

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,23 @@
1-
using System;
2-
using System.Diagnostics;
3-
using System.IO;
4-
using System.Threading.Tasks;
5-
using Microsoft.AspNetCore.Authorization;
1+
using Microsoft.AspNetCore.Authorization;
62
using Microsoft.AspNetCore.Mvc;
73
using Microsoft.Extensions.Options;
8-
using Graph = Microsoft.Graph;
94
using Microsoft.Identity.Web;
5+
using System;
6+
using System.Diagnostics;
7+
using System.IO;
8+
using System.Threading.Tasks;
109
using WebApp_OpenIDConnect_DotNet.Infrastructure;
1110
using WebApp_OpenIDConnect_DotNet.Models;
1211
using WebApp_OpenIDConnect_DotNet.Services;
12+
using Graph = Microsoft.Graph;
1313

1414
namespace WebApp_OpenIDConnect_DotNet.Controllers
1515
{
1616
[Authorize]
1717
public class HomeController : Controller
1818
{
19-
readonly ITokenAcquisition tokenAcquisition;
20-
readonly WebOptions webOptions;
19+
private readonly ITokenAcquisition tokenAcquisition;
20+
private readonly WebOptions webOptions;
2121

2222
public HomeController(ITokenAcquisition tokenAcquisition,
2323
IOptions<WebOptions> webOptionValue)
@@ -35,7 +35,7 @@ public IActionResult Index()
3535
[AuthorizeForScopes(Scopes = new[] { Constants.ScopeUserRead })]
3636
public async Task<IActionResult> Profile()
3737
{
38-
// Initialize the GraphServiceClient.
38+
// Initialize the GraphServiceClient.
3939
Graph::GraphServiceClient graphClient = GetGraphServiceClient(new[] { Constants.ScopeUserRead });
4040

4141
var me = await graphClient.Me.Request().GetAsync();
@@ -73,16 +73,15 @@ public IActionResult Error()
7373
}
7474

7575
[AuthorizeForScopes(Scopes = new[] { GraphScopes.UserReadBasicAll })]
76-
[Authorize(Roles = AppRoles.UserReaders )]
76+
[Authorize(Roles = AppRoles.UserReaders)]
7777
public async Task<IActionResult> Users()
7878
{
79-
// Initialize the GraphServiceClient.
79+
// Initialize the GraphServiceClient.
8080
Graph::GraphServiceClient graphClient = GetGraphServiceClient(new[] { GraphScopes.UserReadBasicAll });
8181

8282
var users = await graphClient.Users.Request().GetAsync();
8383
ViewData["Users"] = users.CurrentPage;
8484

85-
8685
return View();
8786
}
8887
}

0 commit comments

Comments
 (0)