Skip to content

Commit 42bf0c0

Browse files
Kalyan Krishnajmprieur
authored andcommitted
New sample done (#93)
* PS and config done * Coding almost done * A few bits remaining * Final touches to the readme.md * Code review comments addressed * Minor edit
1 parent 6f2c04f commit 42bf0c0

File tree

24 files changed

+713
-198
lines changed

24 files changed

+713
-198
lines changed

.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,3 +67,6 @@
6767
/5-WebApp-AuthZ/5-2-Groups/.vs
6868
/5-WebApp-AuthZ/5-2-Groups/bin/Debug/netcoreapp2.2
6969
/5-WebApp-AuthZ/5-2-Groups/obj
70+
/5-WebApp-AuthZ/5-1-Roles/AppCreationScripts/createdApps.html
71+
/5-WebApp-AuthZ/5-1-Roles/AppCreationScripts/Steps.md
72+
/5-WebApp-AuthZ/5-1-Roles/WebApp-OpenIDConnect-DotNet.csproj.user

5-WebApp-AuthZ-Roles-Groups/README..md

Lines changed: 0 additions & 1 deletion
This file was deleted.

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,8 +49,8 @@ This function removes the Azure AD applications for the sample. These applicatio
4949
# Removes the applications
5050
Write-Host "Cleaning-up applications from tenant '$tenantName'"
5151

52-
Write-Host "Removing 'webApp' (WebApp-OpenIDConnect-DotNet-code-v2) if needed"
53-
$app=Get-AzureADApplication -Filter "DisplayName eq 'WebApp-OpenIDConnect-DotNet-code-v2'"
52+
Write-Host "Removing 'webApp' (WebApp-RolesClaims) if needed"
53+
$app=Get-AzureADApplication -Filter "DisplayName eq 'WebApp-RolesClaims'"
5454

5555
if ($app)
5656
{
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
[CmdletBinding()]
2+
param(
3+
[PSCredential] $Credential,
4+
[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')]
5+
[string] $tenantId
6+
)
7+
8+
Import-Module AzureAD
9+
$ErrorActionPreference = 'Stop'
10+
11+
Function RemoveUser([string]$userPrincipal)
12+
{
13+
$user = Get-AzureADUser -Filter "UserPrincipalName eq '$userPrincipal'"
14+
if ($user)
15+
{
16+
Write-Host "Removing User '($userPrincipal)'"
17+
Remove-AzureADUser -ObjectId $user.ObjectId
18+
}
19+
else {
20+
Write-Host "Failed to remove user '($userPrincipal)'"
21+
}
22+
}
23+
24+
Function CleanupUsers
25+
{
26+
<#
27+
.Description
28+
This function removes the users created in the Azure AD tenant by the CreateUsersAndRoles.ps1 script.
29+
#>
30+
31+
# $tenantId is the Active Directory Tenant. This is a GUID which represents the "Directory ID" of the AzureAD tenant
32+
# into which you want to create the apps. Look it up in the Azure portal in the "Properties" of the Azure AD.
33+
34+
# Login to Azure PowerShell (interactive if credentials are not already provided:
35+
# you'll need to sign-in with creds enabling your to create apps in the tenant)
36+
if (!$Credential -and $TenantId)
37+
{
38+
$creds = Connect-AzureAD -TenantId $tenantId
39+
}
40+
else
41+
{
42+
if (!$TenantId)
43+
{
44+
$creds = Connect-AzureAD -Credential $Credential
45+
}
46+
else
47+
{
48+
$creds = Connect-AzureAD -TenantId $tenantId -Credential $Credential
49+
}
50+
}
51+
52+
if (!$tenantId)
53+
{
54+
$tenantId = $creds.Tenant.Id
55+
}
56+
57+
$tenant = Get-AzureADTenantDetail
58+
59+
$tenantName = ($tenant.VerifiedDomains | Where { $_._Default -eq $True }).Name
60+
61+
$appName = "WebApp-RolesClaims"
62+
63+
# Removes the users created for the application
64+
Write-Host "Removing Users"
65+
RemoveUser -userPrincipal "$appName-DirectoryViewers@$tenantName"
66+
RemoveUser -userPrincipal "$appName-UserReaders@$tenantName"
67+
68+
Write-Host "finished removing users created for this app."
69+
}
70+
71+
# Pre-requisites
72+
if ((Get-Module -ListAvailable -Name "AzureAD") -eq $null) {
73+
Install-Module "AzureAD" -Scope CurrentUser
74+
}
75+
Import-Module AzureAD
76+
$ErrorActionPreference = 'Stop'
77+
78+
CleanupUsers -Credential $Credential -tenantId $TenantId

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

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -178,46 +178,49 @@ Function ConfigureApplications
178178
$user = Get-AzureADUser -ObjectId $creds.Account.Id
179179

180180
# Create the webApp AAD application
181-
Write-Host "Creating the AAD application (WebApp-OpenIDConnect-DotNet-code-v2)"
181+
Write-Host "Creating the AAD application (WebApp-RolesClaims)"
182182
# Get a 2 years application key for the webApp Application
183183
$pw = ComputePassword
184184
$fromDate = [DateTime]::Now;
185185
$key = CreateAppKey -fromDate $fromDate -durationInYears 2 -pw $pw
186186
$webAppAppKey = $pw
187-
$webAppAadApplication = New-AzureADApplication -DisplayName "WebApp-OpenIDConnect-DotNet-code-v2" `
187+
$webAppAadApplication = New-AzureADApplication -DisplayName "WebApp-RolesClaims" `
188188
-HomePage "https://localhost:44321/" `
189189
-LogoutUrl "https://localhost:44321/signout-oidc" `
190190
-ReplyUrls "https://localhost:44321/", "https://localhost:44321/signin-oidc" `
191-
-IdentifierUris "https://$tenantName/WebApp-OpenIDConnect-DotNet-code-v2" `
192-
-AvailableToOtherTenants $True `
191+
-IdentifierUris "https://$tenantName/WebApp-RolesClaims" `
193192
-PasswordCredentials $key `
194193
-Oauth2AllowImplicitFlow $true `
194+
-GroupMembershipClaims "SecurityGroup" `
195195
-PublicClient $False
196196

197197
$currentAppId = $webAppAadApplication.AppId
198-
$webAppServicePrincipal = New-AzureADServicePrincipal -AppId $currentAppId -Tags {WindowsAzureActiveDirectoryIntegratedApp}
198+
$webAppServicePrincipal = New-AzureADServicePrincipal -AppId $currentAppId -Tags {WindowsAzureActiveDirectoryIntegratedApp} -AppRoleAssignmentRequired $true
199199

200200
# add the user running the script as an app owner if needed
201201
$owner = Get-AzureADApplicationOwner -ObjectId $webAppAadApplication.ObjectId
202202
if ($owner -eq $null)
203203
{
204-
Add-AzureADApplicationOwner -ObjectId $webAppAadApplication.ObjectId -RefObjectId $user.ObjectId
205-
Write-Host "'$($user.UserPrincipalName)' added as an application owner to app '$($webAppServicePrincipal.DisplayName)'"
204+
Add-AzureADApplicationOwner -ObjectId $webAppAadApplication.ObjectId -RefObjectId $user.ObjectId
205+
Write-Host "'$($user.UserPrincipalName)' added as an application owner to app '$($webAppServicePrincipal.DisplayName)'"
206+
207+
# assign the current user to the app as well
208+
New-AzureADUserAppRoleAssignment -ObjectId $user.ObjectId -PrincipalId $user.ObjectId -ResourceId $webAppServicePrincipal.ObjectId -Id ([Guid]::Empty)
206209
}
207210

208-
Write-Host "Done creating the webApp application (WebApp-OpenIDConnect-DotNet-code-v2)"
211+
Write-Host "Done creating the webApp application (WebApp-RolesClaims)"
209212

210213
# URL of the AAD application in the Azure portal
211214
# Future? $webAppPortalUrl = "https://portal.azure.com/#@"+$tenantName+"/blade/Microsoft_AAD_RegisteredApps/ApplicationMenuBlade/Overview/appId/"+$webAppAadApplication.AppId+"/objectId/"+$webAppAadApplication.ObjectId+"/isMSAApp/"
212215
$webAppPortalUrl = "https://portal.azure.com/#blade/Microsoft_AAD_RegisteredApps/ApplicationMenuBlade/CallAnAPI/appId/"+$webAppAadApplication.AppId+"/objectId/"+$webAppAadApplication.ObjectId+"/isMSAApp/"
213-
Add-Content -Value "<tr><td>webApp</td><td>$currentAppId</td><td><a href='$webAppPortalUrl'>WebApp-OpenIDConnect-DotNet-code-v2</a></td></tr>" -Path createdApps.html
216+
Add-Content -Value "<tr><td>webApp</td><td>$currentAppId</td><td><a href='$webAppPortalUrl'>WebApp-RolesClaims</a></td></tr>" -Path createdApps.html
214217

215218
$requiredResourcesAccess = New-Object System.Collections.Generic.List[Microsoft.Open.AzureAD.Model.RequiredResourceAccess]
216219

217220
# Add Required Resources Access (from 'webApp' to 'Microsoft Graph')
218221
Write-Host "Getting access from 'webApp' to 'Microsoft Graph'"
219222
$requiredPermissions = GetRequiredPermissions -applicationDisplayName "Microsoft Graph" `
220-
-requiredDelegatedPermissions "User.Read" `
223+
-requiredDelegatedPermissions "User.Read|User.ReadBasic.All|Directory.Read.All" `
221224

222225
$requiredResourcesAccess.Add($requiredPermissions)
223226

@@ -230,6 +233,8 @@ Function ConfigureApplications
230233
Write-Host "Updating the sample code ($configFile)"
231234
$dictionary = @{ "ClientId" = $webAppAadApplication.AppId;"TenantId" = $tenantId;"Domain" = $tenantName;"ClientSecret" = $webAppAppKey };
232235
UpdateTextFile -configFilePath $configFile -dictionary $dictionary
236+
Write-Host ""
237+
Write-Host -ForegroundColor Green "Run the ..\CreateUsersAndRoles.ps1 command to automatically create a number of users, app roles and assign users to these roles or refer to the 'Define your application roles' section in README on how to configure your newly created app further for this sample."
233238

234239
Add-Content -Value "</tbody></table></body></html>" -Path createdApps.html
235240
}
Lines changed: 148 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,148 @@
1+
[CmdletBinding()]
2+
param(
3+
[PSCredential] $Credential,
4+
[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')]
5+
[string] $tenantId
6+
)
7+
8+
<#
9+
This script creates the following artefacts in the Azure AD tenant.
10+
1) A number of App roles
11+
2) A set of users and assigns them to the app roles.
12+
13+
Before running this script you need to install the AzureAD cmdlets as an administrator.
14+
For this:
15+
1) Run Powershell as an administrator
16+
2) in the PowerShell window, type: Install-Module AzureAD
17+
18+
There are four ways to run this script. For more information, read the AppCreationScripts.md file in the same folder as this script.
19+
#>
20+
21+
# Create an application role of given name and description
22+
Function CreateAppRole([string] $Name, [string] $Description)
23+
{
24+
$appRole = New-Object Microsoft.Open.AzureAD.Model.AppRole
25+
$appRole.AllowedMemberTypes = New-Object System.Collections.Generic.List[string]
26+
$appRole.AllowedMemberTypes.Add("User");
27+
$appRole.DisplayName = $Name
28+
$appRole.Id = New-Guid
29+
$appRole.IsEnabled = $true
30+
$appRole.Description = $Description
31+
$appRole.Value = $Name;
32+
return $appRole
33+
}
34+
35+
Function CreateUserRepresentingAppRole([string]$appName, $role, [string]$tenantName)
36+
{
37+
$password = "test123456789."
38+
$displayName = $appName +"-" + $role.Value
39+
$userEmail = $displayName + "@" + $tenantName
40+
$nickName = $role.Value
41+
42+
CreateUser -displayName $displayName -nickName $nickName -tenantName $tenantName
43+
}
44+
45+
Function CreateUser([string]$displayName, [string]$nickName, [string]$tenantName)
46+
{
47+
$password = "test123456789."
48+
$userEmail = $displayName + "@" + $tenantName
49+
$passwordProfile = New-Object Microsoft.Open.AzureAD.Model.PasswordProfile($password, $false, $false)
50+
51+
New-AzureADUser -DisplayName $displayName -PasswordProfile $passwordProfile -AccountEnabled $true -MailNickName $nickName -UserPrincipalName $userEmail
52+
}
53+
54+
Function CreateRolesUsersAndRoleAssignments
55+
{
56+
<#.Description
57+
This function creates the
58+
#>
59+
60+
# $tenantId is the Active Directory Tenant. This is a GUID which represents the "Directory ID" of the AzureAD tenant
61+
# into which you want to create the apps. Look it up in the Azure portal in the "Properties" of the Azure AD.
62+
63+
# Login to Azure PowerShell (interactive if credentials are not already provided:
64+
# you'll need to sign-in with creds enabling your to create apps in the tenant)
65+
if (!$Credential -and $TenantId)
66+
{
67+
$creds = Connect-AzureAD -TenantId $tenantId
68+
}
69+
else
70+
{
71+
if (!$TenantId)
72+
{
73+
$creds = Connect-AzureAD -Credential $Credential
74+
}
75+
else
76+
{
77+
$creds = Connect-AzureAD -TenantId $tenantId -Credential $Credential
78+
}
79+
}
80+
81+
if (!$tenantId)
82+
{
83+
$tenantId = $creds.Tenant.Id
84+
}
85+
86+
$tenant = Get-AzureADTenantDetail
87+
$tenantName = ($tenant.VerifiedDomains | Where { $_._Default -eq $True }).Name
88+
89+
# Get the user running the script
90+
$user = Get-AzureADUser -ObjectId $creds.Account.Id
91+
92+
# Add application Roles
93+
$directoryViewerRole = CreateAppRole -Name "DirectoryViewers" -Description "Directory viewers can view objects in the whole directory."
94+
$userreaderRole = CreateAppRole -Name "UserReaders" -Description "User readers can read basic profiles of all users in the directory"
95+
96+
$appRoles = New-Object System.Collections.Generic.List[Microsoft.Open.AzureAD.Model.AppRole]
97+
$appRoles.Add($directoryViewerRole)
98+
$appRoles.Add($userreaderRole)
99+
100+
# Add the roles
101+
Write-Host "Adding app roles to to the app 'WebApp-RolesClaims' in tenant '$tenantName'"
102+
103+
$app=Get-AzureADApplication -Filter "DisplayName eq 'WebApp-RolesClaims'"
104+
105+
if ($app)
106+
{
107+
$servicePrincipal = Get-AzureADServicePrincipal -Filter "AppId eq '$($app.AppId)'"
108+
109+
Set-AzureADApplication -ObjectId $app.ObjectId -AppRoles $appRoles
110+
Write-Host "Successfully added app roles to the app 'WebApp-RolesClaims'."
111+
112+
$appName = $app.DisplayName
113+
114+
Write-Host "Creating users and assigning them to roles."
115+
116+
# Create users
117+
# ------
118+
# Make sure that the user who is running this script is assigned to the Directory viewer role
119+
Write-Host "Adding '$($user.DisplayName)' as a member of the '$($directoryViewerRole.DisplayName)' role"
120+
$userAssignment = New-AzureADUserAppRoleAssignment -ObjectId $user.ObjectId -PrincipalId $user.ObjectId -ResourceId $servicePrincipal.ObjectId -Id $directoryViewerRole.Id
121+
122+
# Creating a directory viewer
123+
Write-Host "Creating a user and assigning to '$($directoryViewerRole.DisplayName)' role"
124+
$aDirectoryViewer = CreateUserRepresentingAppRole $appName $directoryViewerRole $tenantName
125+
$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+
128+
# Creating a users reader
129+
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.'"
133+
}
134+
else {
135+
Write-Host "Failed to add app roles to the app 'WebApp-RolesClaims'."
136+
}
137+
138+
Write-Host -ForegroundColor Green "Run the ..\CleanupUsersAndRoles.ps1 command to remove users created for this sample's application ."
139+
}
140+
141+
# Pre-requisites
142+
if ((Get-Module -ListAvailable -Name "AzureAD") -eq $null) {
143+
Install-Module "AzureAD" -Scope CurrentUser
144+
}
145+
Import-Module AzureAD
146+
$ErrorActionPreference = 'Stop'
147+
148+
CreateRolesUsersAndRoleAssignments -Credential $Credential -tenantId $TenantId

5-WebApp-AuthZ/5-1-Roles/AppCreationScripts/sample.json

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
{
22
"Sample": {
3-
"Title": "Using the Microsoft identity platform to call the Microsoft Graph API from an An ASP.NET Core 2.x Web App, on behalf of a user signing-in using their work and school or Microsoft personal account",
4-
"Level": 200,
3+
"Title": "Add authorization using app roles & roles claims to an ASP.NET Core Web app thats signs-in users with the Microsoft identity platform",
4+
"Level": 300,
55
"Client": "ASP.NET Core 2.x Web App",
66
"Service": "Microsoft Graph",
7-
"RepositoryUrl": "active-directory-aspnetcore-webapp-openidconnect-v2",
7+
"RepositoryUrl": "microsoft-identity-platform-aspnetcore-webapp-tutorial",
88
"Endpoint": "AAD v2.0"
99
},
1010

@@ -14,17 +14,21 @@
1414
"AADApps": [
1515
{
1616
"Id": "webApp",
17-
"Name": "WebApp-OpenIDConnect-DotNet-code-v2",
17+
"Name": "WebApp-RolesClaims",
1818
"Kind": "WebApp",
19+
"Audience": "AzureADMyOrg",
1920
"HomePage": "https://localhost:44321/",
2021
"ReplyUrls": "https://localhost:44321/, https://localhost:44321/signin-oidc",
2122
"LogoutUrl": "https://localhost:44321/signout-oidc",
2223
"PasswordCredentials": "Auto",
24+
"GroupMembershipClaims": "SecurityGroup",
2325
"RequiredResourcesAccess": [
2426
{
2527
"Resource": "Microsoft Graph",
26-
"DelegatedPermissions": [ "User.Read" ]
28+
"DelegatedPermissions": [ "User.Read", "User.ReadBasic.All","Directory.Read.All" ]
2729
}
30+
],"ManualSteps": [
31+
{ "Comment": "Run the ..\\CreateUsersAndRoles.ps1 command to automatically create a number of users, app roles and assign users to these roles or refer to the 'Define your application roles' section in README on how to configure your newly created app further for this sample." }
2832
]
2933
}
3034
],

0 commit comments

Comments
 (0)