Skip to content

Commit 45d5bd9

Browse files
author
Kalyan Krishna
committed
Work in progress
1 parent f615524 commit 45d5bd9

File tree

16 files changed

+216
-189
lines changed

16 files changed

+216
-189
lines changed

2-WebApp-graph-user/2-2-TokenCache/AppCreationScripts/Configure.ps1

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,7 @@ Function ConfigureApplications
227227

228228
$requiredResourcesAccess.Add($requiredPermissions)
229229

230+
230231
Set-AzureADApplication -ObjectId $webAppAadApplication.ObjectId -RequiredResourceAccess $requiredResourcesAccess
231232
Write-Host "Granted permissions."
232233

4-WebApp-your-API/AppCreationScripts/Cleanup.ps1

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ 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
{

4-WebApp-your-API/AppCreationScripts/Configure.ps1

Lines changed: 76 additions & 5 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
{
@@ -133,19 +133,55 @@ Function UpdateTextFile([string] $configFilePath, [System.Collections.HashTable]
133133

134134
Set-Content -Path $configFilePath -Value $lines -Force
135135
}
136+
<#.Description
137+
This function creates a new Azure AD scope (OAuth2Permission) with default and provided values
138+
#>
139+
Function CreateScope( [string] $value, [string] $userConsentDisplayName, [string] $userConsentDescription, [string] $adminConsentDisplayName, [string] $adminConsentDescription)
140+
{
141+
$scope = New-Object Microsoft.Open.AzureAD.Model.OAuth2Permission
142+
$scope.Id = New-Guid
143+
$scope.Value = $value
144+
$scope.UserConsentDisplayName = $userConsentDisplayName
145+
$scope.UserConsentDescription = $userConsentDescription
146+
$scope.AdminConsentDisplayName = $adminConsentDisplayName
147+
$scope.AdminConsentDescription = $adminConsentDescription
148+
$scope.IsEnabled = $true
149+
$scope.Type = "User"
150+
return $scope
151+
}
136152

153+
<#.Description
154+
This function creates a new Azure AD AppRole with default and provided values
155+
#>
156+
Function CreateAppRole([string] $types, [string] $name, [string] $description)
157+
{
158+
$appRole = New-Object Microsoft.Open.AzureAD.Model.AppRole
159+
$appRole.AllowedMemberTypes = New-Object System.Collections.Generic.List[string]
160+
$typesArr = $types.Split(',')
161+
foreach($type in $typesArr)
162+
{
163+
$appRole.AllowedMemberTypes.Add($type);
164+
}
165+
$appRole.DisplayName = $name
166+
$appRole.Id = New-Guid
167+
$appRole.IsEnabled = $true
168+
$appRole.Description = $description
169+
$appRole.Value = $name;
170+
return $appRole
171+
}
137172

138173
Set-Content -Value "<html><body><table>" -Path createdApps.html
139174
Add-Content -Value "<thead><tr><th>Application</th><th>AppId</th><th>Url in the Azure portal</th></tr></thead><tbody>" -Path createdApps.html
140175

176+
$ErrorActionPreference = "Stop"
177+
141178
Function ConfigureApplications
142179
{
143180
<#.Description
144181
This function creates the Azure AD applications for the sample in the provided Azure AD tenant and updates the
145182
configuration files in the client and service project of the visual studio solution (App.Config and Web.Config)
146183
so that they are consistent with the Applications parameters
147184
#>
148-
149185
$commonendpoint = "common"
150186

151187
# $tenantId is the Active Directory Tenant. This is a GUID which represents the "Directory ID" of the AzureAD tenant
@@ -177,17 +213,19 @@ Function ConfigureApplications
177213
$tenant = Get-AzureADTenantDetail
178214
$tenantName = ($tenant.VerifiedDomains | Where { $_._Default -eq $True }).Name
179215

180-
# Get the user running the script
216+
# Get the user running the script to add the user as the app owner
181217
$user = Get-AzureADUser -ObjectId $creds.Account.Id
182218

183219
# Create the service AAD application
184220
Write-Host "Creating the AAD application (TodoListService-aspnetcore-webapi)"
221+
# create the application
185222
$serviceAadApplication = New-AzureADApplication -DisplayName "TodoListService-aspnetcore-webapi" `
186223
-HomePage "https://localhost:44351/" `
187224
-PublicClient $False
188225
$serviceIdentifierUri = 'api://'+$serviceAadApplication.AppId
189226
Set-AzureADApplication -ObjectId $serviceAadApplication.ObjectId -IdentifierUris $serviceIdentifierUri
190227

228+
# create the service principal of the newly created application
191229
$currentAppId = $serviceAadApplication.AppId
192230
$serviceServicePrincipal = New-AzureADServicePrincipal -AppId $currentAppId -Tags {WindowsAzureActiveDirectoryIntegratedApp}
193231

@@ -199,6 +237,35 @@ Function ConfigureApplications
199237
Write-Host "'$($user.UserPrincipalName)' added as an application owner to app '$($serviceServicePrincipal.DisplayName)'"
200238
}
201239

240+
# rename the user_impersonation scope if it exists to match the readme steps or add a new scope
241+
$scopes = New-Object System.Collections.Generic.List[Microsoft.Open.AzureAD.Model.OAuth2Permission]
242+
243+
if ($scopes.Count -ge 0)
244+
{
245+
# add all existing scopes first
246+
$serviceAadApplication.Oauth2Permissions | foreach-object { $scopes.Add($_) }
247+
248+
$scope = $serviceAadApplication.Oauth2Permissions | Where-Object { $_.Value -eq "User_impersonation" }
249+
250+
if ($scope -ne $null)
251+
{
252+
$scope.Value = "access_as_user"
253+
}
254+
else
255+
{
256+
# Add scope
257+
$scope = CreateScope -value "access_as_user" `
258+
-userConsentDisplayName "Access TodoListService-aspnetcore-webapi" `
259+
-userConsentDescription "Allow the application to access TodoListService-aspnetcore-webapi on your behalf." `
260+
-adminConsentDisplayName "Access TodoListService-aspnetcore-webapi" `
261+
-adminConsentDescription "Allows the app to have the same access to information in the directory on behalf of the signed-in user."
262+
263+
$scopes.Add($scope)
264+
}
265+
}
266+
267+
# add/update scopes
268+
Set-AzureADApplication -ObjectId $serviceAadApplication.ObjectId -OAuth2Permission $scopes
202269

203270
Write-Host "Done creating the service application (TodoListService-aspnetcore-webapi)"
204271

@@ -207,13 +274,15 @@ Function ConfigureApplications
207274
$servicePortalUrl = "https://portal.azure.com/#blade/Microsoft_AAD_RegisteredApps/ApplicationMenuBlade/CallAnAPI/appId/"+$serviceAadApplication.AppId+"/objectId/"+$serviceAadApplication.ObjectId+"/isMSAApp/"
208275
Add-Content -Value "<tr><td>service</td><td>$currentAppId</td><td><a href='$servicePortalUrl'>TodoListService-aspnetcore-webapi</a></td></tr>" -Path createdApps.html
209276

277+
210278
# Create the client AAD application
211279
Write-Host "Creating the AAD application (TodoListClient-aspnetcore-webapi)"
212280
# Get a 2 years application key for the client Application
213281
$pw = ComputePassword
214282
$fromDate = [DateTime]::Now;
215283
$key = CreateAppKey -fromDate $fromDate -durationInYears 2 -pw $pw
216284
$clientAppKey = $pw
285+
# create the application
217286
$clientAadApplication = New-AzureADApplication -DisplayName "TodoListClient-aspnetcore-webapi" `
218287
-HomePage "https://localhost:44321/" `
219288
-LogoutUrl "https://localhost:44321/signout-oidc" `
@@ -223,6 +292,7 @@ Function ConfigureApplications
223292
-Oauth2AllowImplicitFlow $true `
224293
-PublicClient $False
225294

295+
# create the service principal of the newly created application
226296
$currentAppId = $clientAadApplication.AppId
227297
$clientServicePrincipal = New-AzureADServicePrincipal -AppId $currentAppId -Tags {WindowsAzureActiveDirectoryIntegratedApp}
228298

@@ -247,7 +317,7 @@ Function ConfigureApplications
247317
# Add Required Resources Access (from 'client' to 'service')
248318
Write-Host "Getting access from 'client' to 'service'"
249319
$requiredPermissions = GetRequiredPermissions -applicationDisplayName "TodoListService-aspnetcore-webapi" `
250-
-requiredDelegatedPermissions "user_impersonation" `
320+
-requiredDelegatedPermissions "access_as_user" `
251321

252322
$requiredResourcesAccess.Add($requiredPermissions)
253323

@@ -273,7 +343,8 @@ Function ConfigureApplications
273343
# Pre-requisites
274344
if ((Get-Module -ListAvailable -Name "AzureAD") -eq $null) {
275345
Install-Module "AzureAD" -Scope CurrentUser
276-
}
346+
}
347+
277348
Import-Module AzureAD
278349

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

4-WebApp-your-API/AppCreationScripts/sample.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232
"RequiredResourcesAccess": [
3333
{
3434
"Resource": "service",
35-
"DelegatedPermissions": [ "user_impersonation" ]
35+
"DelegatedPermissions": [ "access_as_user" ]
3636
}
3737
]
3838
}

4-WebApp-your-API/Client/appsettings.json

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,24 @@
11
{
22
"AzureAd": {
33
"Instance": "https://login.microsoftonline.com/",
4-
"Domain": "[Enter the domain of your tenant, e.g. contoso.onmicrosoft.com]",
5-
"TenantId": "[Enter 'common', or 'organizations' or the Tenant Id (Obtained from the Azure portal. Select 'Endpoints' from the 'App registrations' blade and use the GUID in any of the URLs), e.g. da41245a5-11b3-996c-00a8-4d99re19f292]",
6-
"ClientId": "[Enter the Client Id of the web app (Application ID obtained from the Azure portal), e.g. ba74781c2-53c2-442a-97c2-3d60re42f403]",
4+
"Domain": "kkaad.onmicrosoft.com",
5+
"TenantId": "979f4440-75dc-4664-b2e1-2cafa0ac67d1",
6+
"ClientId": "30fcdffd-4f38-49ba-bceb-d8063ebe4b0e",
77
"CallbackPath": "/signin-oidc",
88
"SignedOutCallbackPath ": "/signout-callback-oidc",
99

1010
// To call an API
11-
"ClientSecret": "[Copy the client secret added to the app from the Azure portal]"
11+
"ClientSecret": "m9lTgLGbq7CXXhfTtQCak3sYdYnqyQsbzBh5ol+X9zA= "GIgeZIAiicWVD4ImenEIx8TM4BPAfTxCGtzstVChkKs=";
1212
},
1313
"TodoList": {
1414
/*
15-
TodoListScope is the scope of the Web API you want to call. This can be: "api://90b0be48-155d-4ba5-ba7a-0fddd1b68795/user_impersonation",
15+
TodoListScope is the scope of the Web API you want to call. This can be: "api://8f085429-c424-45c4-beb3-75f6f0a7924f/user_impersonation",
1616
- a scope for a V2 application (for instance api://b3682cc7-8b30-4bd2-aaba-080c6bf0fd31/access_as_user)
1717
- a scope corresponding to a V1 application (for instance <GUID>/user_impersonation, where <GUID> is the
1818
clientId of a V1 application, created in the https://portal.azure.com portal.
1919
*/
20-
"TodoListScope": "api://[Enter_client_ID_Of_TodoListService-v2_from_Azure_Portal,_e.g._2ec40e65-ba09-4853-bcde-bcb60029e596]/user_impersonation",
21-
"TodoListBaseAddress": "https://localhost:44351"
20+
"TodoListScope": "api://8f085429-c424-45c4-beb3-75f6f0a7924f/user_impersonation",
21+
"TodoListBaseAddress": "https://localhost:44351/",
2222

2323
},
2424
"Logging": {

4-WebApp-your-API/TodoListService/appsettings.json

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
{
22
"AzureAd": {
33
"Instance": "https://login.microsoftonline.com/",
4-
"ClientId": "[Enter the Client Id of the service (Application ID obtained from the Azure portal), e.g. ba74781c2-53c2-442a-97c2-3d60re42f403]",
5-
"Domain": "[Enter the domain of your tenant, e.g. contoso.onmicrosoft.com]",
6-
"TenantId": "[Enter 'common', or 'organizations' or the Tenant Id (Obtained from the Azure portal. Select 'Endpoints' from the 'App registrations' blade and use the GUID in any of the URLs), e.g. da41245a5-11b3-996c-00a8-4d99re19f292]"
4+
"ClientId": "8f085429-c424-45c4-beb3-75f6f0a7924f",
5+
"Domain": "kkaad.onmicrosoft.com",
6+
"TenantId": "979f4440-75dc-4664-b2e1-2cafa0ac67d1",
77
},
88
"Kestrel": {
99
"Endpoints": {
@@ -18,4 +18,4 @@
1818
}
1919
},
2020
"AllowedHosts": "*"
21-
}
21+
}

5-WebApp-AuthZ/5-2-Groups/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-2-Groups/AppCreationScripts/Cleanup.ps1

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ 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
{

5-WebApp-AuthZ/5-2-Groups/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-GroupClaims" `
190192
-HomePage "https://localhost:44321/" `
191193
-LogoutUrl "https://localhost:44321/signout-oidc" `
@@ -196,6 +198,7 @@ Function ConfigureApplications
196198
-Oauth2AllowImplicitFlow $true `
197199
-PublicClient $False
198200

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

@@ -207,6 +210,7 @@ Function ConfigureApplications
207210
Write-Host "'$($user.UserPrincipalName)' added as an application owner to app '$($webAppServicePrincipal.DisplayName)'"
208211
}
209212

213+
210214
Write-Host "Done creating the webApp application (WebApp-GroupClaims)"
211215

212216
# URL of the AAD application in the Azure portal
@@ -239,7 +243,8 @@ Function ConfigureApplications
239243
# Pre-requisites
240244
if ((Get-Module -ListAvailable -Name "AzureAD") -eq $null) {
241245
Install-Module "AzureAD" -Scope CurrentUser
242-
}
246+
}
247+
243248
Import-Module AzureAD
244249

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

5-WebApp-AuthZ/5-2-Groups/Controllers/UserProfileController.cs

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
using Microsoft.AspNetCore.Mvc;
1+
using Microsoft.AspNetCore.Authorization;
2+
using Microsoft.AspNetCore.Mvc;
23
using Microsoft.Graph;
34
using Microsoft.Identity.Web;
45
using System.Collections.Generic;
@@ -8,6 +9,7 @@
89

910
namespace WebApp_OpenIDConnect_DotNet.Controllers
1011
{
12+
// [Authorize(Roles = "8873daa2-17af-4e72-973e-930c94ef7549")] // Using groups ids in the Authorize attribute
1113
public class UserProfileController : Controller
1214
{
1315
private readonly ITokenAcquisition tokenAcquisition;
@@ -19,9 +21,12 @@ public UserProfileController(ITokenAcquisition tokenAcquisition, IMSGraphService
1921
this.graphService = MSGraphService;
2022
}
2123

22-
[AuthorizeForScopes(Scopes = new[] { Constants.ScopeUserRead, Constants.ScopeDirectoryReadAll })]
24+
[AuthorizeForScopes(Scopes = new[] { Constants.ScopeUserRead, Constants.ScopeDirectoryReadAll })]
2325
public async Task<IActionResult> Index()
2426
{
27+
// Using group ids/names in the IsInRole method
28+
// var isinrole = User.IsInRole("8873daa2-17af-4e72-973e-930c94ef7549");
29+
2530
string accessToken = await tokenAcquisition.GetAccessTokenOnBehalfOfUserAsync(new[] { Constants.ScopeUserRead, Constants.ScopeDirectoryReadAll });
2631

2732
User me = await graphService.GetMeAsync(accessToken);

0 commit comments

Comments
 (0)