Skip to content

Permission update from Directory.Read.All to GroupMember.Read.All #388

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 23 commits into from
Sep 24, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .github/ISSUE_TEMPLATE.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,10 @@ Please add an 'x' for the scenario(s) where you found an issue
1. [ ] With specific token caches: [2-WebApp-graph-user/2-2-TokenCache](../blob/master/2-WebApp-graph-user/2-2-TokenCache)
1. [ ] Calling Microsoft Graph in national clouds: [2-WebApp-graph-user/2-4-Sovereign-Call-MSGraph](../blob/master/2-WebApp-graph-user/2-4-Sovereign-Call-MSGraph)
1. [ ] Web app calling several APIs [3-WebApp-multi-APIs](../blob/master/3-WebApp-multi-APIs)
1. [ ] Web app calling your own Web API [4-WebApp-your-API](../blob/master/4-WebApp-your-API)
1. [ ] Web app calling your own Web API
1. [ ] with a work and school account in your organization: [4-WebApp-your-API/4-1-MyOrg](../blob/master/4-WebApp-your-API/4-1-MyOrg)
1. [ ] with B2C users: [4-WebApp-your-API/4-2-B2C](../blob/master/4-WebApp-your-API/4-2-B2C)
1. [ ] with any work and school account: [4-WebApp-your-API/4-3-AnyOrg](../blob/master/4-WebApp-your-API/4-3-AnyOrg)
1. Web app restricting users
1. [ ] by Roles: [5-WebApp-AuthZ/5-1-Roles](../blob/master/5-WebApp-AuthZ/5-1-Roles)
1. [ ] by Groups: [5-WebApp-AuthZ/5-2-Groups](../blob/master/5-WebApp-AuthZ/5-2-Groups)
Expand Down
60 changes: 40 additions & 20 deletions 5-WebApp-AuthZ/5-2-Groups/AppCreationScripts/AppCreationScripts.md
Original file line number Diff line number Diff line change
@@ -1,35 +1,47 @@
# Registering the sample apps with Microsoft identity platform and updating the configuration files using PowerShell scripts
# Registering the sample apps with the Microsoft identity platform and updating the configuration files using PowerShell

## Overview

### Quick summary

1. On Windows run PowerShell and navigate to the root of the cloned directory
1. On Windows run PowerShell as **Administrator** and navigate to the root of the cloned directory
1. In PowerShell run:

```PowerShell
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process -Force
```

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)

```PowerShell
cd .\AppCreationScripts\
.\Configure.ps1
```

1. Open the Visual Studio solution and click start

### More details

The following paragraphs:

- [Present the scripts](#presentation-of-the-scripts) and explain their [usage patterns](#usage-pattern-for-tests-and-devops-scenarios) for test and DevOps scenarios.
- Explain the [pre-requisites](#pre-requisites)
- Explain [four ways of running the scripts](#four-ways-to-run-the-script):
- [Interactively](#option-1-interactive) to create the app in your home tenant
- [Passing credentials](#option-2-non-interactive) to create the app in your home tenant
- [Interactively in a specific tenant](#option-3-interactive-but-create-apps-in-a-specified-tenant)
- [Passing credentials in a specific tenant](#option-4-non-interactive-and-create-apps-in-a-specified-tenant)
- [Passing environment name, for Sovereign clouds](#running-the-script-on-azure-sovereign-clouds)

## Goal of the scripts
- [Registering the sample apps with the Microsoft identity platform and updating the configuration files using PowerShell](#Registering-the-sample-apps-with-the-Microsoft-identity-platform-and-updating-the-configuration-files-using-PowerShell)
- [Overview](#Overview)
- [Quick summary](#Quick-summary)
- [More details](#More-details)
- [Goal of the provided scripts](#Goal-of-the-provided-scripts)
- [Presentation of the scripts](#Presentation-of-the-scripts)
- [Usage pattern for tests and DevOps scenarios](#Usage-pattern-for-tests-and-DevOps-scenarios)
- [How to use the app creation scripts?](#How-to-use-the-app-creation-scripts)
- [Pre-requisites](#Pre-requisites)
- [Run the script and start running](#Run-the-script-and-start-running)
- [Four ways to run the script](#Four-ways-to-run-the-script)
- [Option 1 (interactive)](#Option-1-interactive)
- [Option 2 (non-interactive)](#Option-2-non-interactive)
- [Option 3 (Interactive, but create apps in a specified tenant)](#Option-3-Interactive-but-create-apps-in-a-specified-tenant)
- [Option 4 (non-interactive, and create apps in a specified tenant)](#Option-4-non-interactive-and-create-apps-in-a-specified-tenant)
- [Running the script on Azure Sovereign clouds](#Running-the-script-on-Azure-Sovereign-clouds)

## Goal of the provided scripts

### Presentation of the scripts

Expand All @@ -56,36 +68,43 @@ The `Configure.ps1` will stop if it tries to create an Azure AD application whic
### Pre-requisites

1. Open PowerShell (On Windows, press `Windows-R` and type `PowerShell` in the search window)
2. Navigate to the root directory of the project.
3. Until you change it, the default [Execution Policy](https:/go.microsoft.com/fwlink/?LinkID=135170) for scripts is usually `Restricted`. In order to run the PowerShell script you need to set the Execution Policy to `RemoteSigned`. You can set this just for the current PowerShell process by running the command:
1. Navigate to the root directory of the project.
1. Until you change it, the default [Execution Policy](https:/go.microsoft.com/fwlink/?LinkID=135170) for scripts is usually `Restricted`. In order to run the PowerShell script you need to set the Execution Policy to `RemoteSigned`. You can set this just for the current PowerShell process by running the command:

```PowerShell
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process
```
### (Optionally) install AzureAD PowerShell modules

1. ### (Optionally) install AzureAD PowerShell modules
2.
The scripts install the required PowerShell module (AzureAD) for the current user if needed. However, if you want to install if for all users on the machine, you can follow the following steps:

4. If you have never done it already, in the PowerShell window, install the AzureAD PowerShell modules. For this:
1. If you have never done it already, in the PowerShell window, install the AzureAD PowerShell modules. For this:

1. Open PowerShell as admin (On Windows, Search Powershell in the search bar, right click on it and select Run as administrator).
2. Type:

```PowerShell
Install-Module AzureAD
```

or if you cannot be administrator on your machine, run:

```PowerShell
Install-Module AzureAD -Scope CurrentUser
```

### Run the script and start running

5. Go to the `AppCreationScripts` sub-folder. From the folder where you cloned the repo,
1. Go to the `AppCreationScripts` sub-folder. From the folder where you cloned the repo,

```PowerShell
cd AppCreationScripts
```
6. Run the scripts. See below for the [four options](#four-ways-to-run-the-script) to do that.
7. Open the Visual Studio solution, and in the solution's context menu, choose **Set Startup Projects**.
8. select **Start** for the projects

1. Run the scripts. See below for the [four options](#four-ways-to-run-the-script) to do that.
1. Open the Visual Studio solution, and in the solution's context menu, choose **Set Startup Projects**.
1. select **Start** for the projects

You're done. this just works!

Expand Down Expand Up @@ -123,6 +142,7 @@ Of course, in real life, you might already get the password as a `SecureString`.
#### Option 3 (Interactive, but create apps in a specified tenant)

if you want to create the apps in a particular tenant, you can use the following option:

- open the [Azure portal](https://portal.azure.com)
- Select the Azure Active directory you are interested in (in the combo-box below your name on the top right of the browser window)
- Find the "Active Directory" object in this tenant
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,11 @@

$ErrorActionPreference = "Stop"

# ObjectId of the user to be assigned to these security groups. The ObjectId can be obtained via Graph Explorer or in the "Users" blade on the portal.
$usersobjectId = "695a3e1d-2e9f-4d24-aa3c-ac795c16f25c"

Get-AzureADUser -ObjectId $usersobjectId

# ObjectId of the user to be assigned to these security groups. The ObjectId can be obtained via Graph Explorer or in the "Users" blade on the portal.
$usersobjectId = "5b6e08a5-7789-4ae0-a4cb-3d73b4097752"
$groupNamePrefix = "TestGroup"
$numberOfGroupsToCreate = 222;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,12 @@ $numberOfGroupsToDelete = 222;
for($i = 1; $i -le $numberOfGroupsToDelete; $i++)
{
$groupName = $groupNamePrefix + $i
$group = Get-AzureADGroup -SearchString $groupName
Remove-AzureADGroup -ObjectId $group.ObjectId
Write-Host "Successfully deleted $($group.DisplayName)"
$groups = Get-AzureADGroup -SearchString $groupName

Foreach ($group in $groups)
{
Write-Host "Trying to delete group $($group.DisplayName)"
Remove-AzureADGroup -ObjectId $group.ObjectId
Write-Host "Successfully deleted $($group.DisplayName)"
}
}
2 changes: 1 addition & 1 deletion 5-WebApp-AuthZ/5-2-Groups/AppCreationScripts/Cleanup.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ param(
[string] $azureEnvironmentName
)

#Requires -Modules AzureAD
#Requires -Modules AzureAD -RunAsAdministrator


if ($null -eq (Get-Module -ListAvailable -Name "AzureAD")) {
Expand Down
18 changes: 14 additions & 4 deletions 5-WebApp-AuthZ/5-2-Groups/AppCreationScripts/Configure.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ param(
[string] $azureEnvironmentName
)

#Requires -Modules AzureAD
#Requires -Modules AzureAD -RunAsAdministrator

<#
This script creates the Azure AD applications needed for this sample and updates the configuration files
Expand Down Expand Up @@ -206,7 +206,6 @@ Function ConfigureApplications
-IdentifierUris "https://$tenantName/WebApp-GroupClaims" `
-PasswordCredentials $key `
-GroupMembershipClaims "SecurityGroup" `
-Oauth2AllowImplicitFlow $true `
-PublicClient $False

# create the service principal of the newly created application
Expand Down Expand Up @@ -234,7 +233,7 @@ Function ConfigureApplications
# Add Required Resources Access (from 'webApp' to 'Microsoft Graph')
Write-Host "Getting access from 'webApp' to 'Microsoft Graph'"
$requiredPermissions = GetRequiredPermissions -applicationDisplayName "Microsoft Graph" `
-requiredDelegatedPermissions "Directory.Read.All" `
-requiredDelegatedPermissions "User.Read|GroupMember.Read.All" `

$requiredResourcesAccess.Add($requiredPermissions)

Expand All @@ -244,10 +243,21 @@ Function ConfigureApplications

# Update config file for 'webApp'
$configFile = $pwd.Path + "\..\appsettings.json"

Write-Host "Updating the sample code ($configFile)"
$dictionary = @{ "ClientId" = $webAppAadApplication.AppId;"TenantId" = $tenantId;"Domain" = $tenantName;"ClientSecret" = $webAppAppKey };
UpdateTextFile -configFilePath $configFile -dictionary $dictionary

Write-Host ""
Write-Host -ForegroundColor Green "------------------------------------------------------------------------------------------------"
Write-Host "IMPORTANT: Please follow the instructions below to complete a few manual step(s) in the Azure portal":
Write-Host "- For 'webApp'"
Write-Host " - Navigate to '$webAppPortalUrl'"
Write-Host " - Navigate to the API Permissions page and select 'Grant admin consent for (your tenant)'" -ForegroundColor Red
Write-Host " - On Azure Portal, create a security group named GroupAdmin, assign some users to it, and configure your ID and Access token to emit GroupID in your app registration. Configure the value for 'GroupAdmin' key in appsettings.json." -ForegroundColor Red
Write-Host " - On Azure Portal, create a security group named GroupMember, assign some users to it, and configure your ID and Access token to emit GroupID in your app registration. Configure the value for 'GroupMember' key in appsettings.json." -ForegroundColor Red

Write-Host -ForegroundColor Green "------------------------------------------------------------------------------------------------"

Add-Content -Value "</tbody></table></body></html>" -Path createdApps.html
}

Expand Down
15 changes: 13 additions & 2 deletions 5-WebApp-AuthZ/5-2-Groups/AppCreationScripts/sample.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,18 @@
"RequiredResourcesAccess": [
{
"Resource": "Microsoft Graph",
"DelegatedPermissions": [ "Directory.Read.All" ]
"DelegatedPermissions": [ "User.Read", "GroupMember.Read.All" ]
}
],
"ManualSteps": [
{
"Comment": "Navigate to the API Permissions page and select 'Grant admin consent for (your tenant)'"
},
{
"Comment": "On Azure Portal, create a security group named GroupAdmin, assign some users to it, and configure your ID and Access token to emit GroupID in your app registration. Configure the value for 'GroupAdmin' key in appsettings.json."
},
{
"Comment": "On Azure Portal, create a security group named GroupMember, assign some users to it, and configure your ID and Access token to emit GroupID in your app registration. Configure the value for 'GroupMember' key in appsettings.json."
}
]
}
Expand All @@ -40,7 +51,7 @@
"CodeConfiguration": [
{
"App": "webApp",
"SettingKind": "JSon",
"SettingKind": "JSON",
"SettingFile": "\\..\\appsettings.json",
"Mappings": [
{
Expand Down
15 changes: 15 additions & 0 deletions 5-WebApp-AuthZ/5-2-Groups/Controllers/AccountController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace WebApp_OpenIDConnect_DotNet.Controllers
{
public class AccountController : Controller
{
[Authorize]
public IActionResult SignOut()
{
HttpContext.Session.Clear();
return RedirectToAction("SignOut", "Account", new { area = "MicrosoftIdentity" });
}
}
}
12 changes: 10 additions & 2 deletions 5-WebApp-AuthZ/5-2-Groups/Controllers/HomeController.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using System.Security.Claims;
using WebApp_OpenIDConnect_DotNet.Models;
using Microsoft.AspNetCore.Http;
using WebApp_OpenIDConnect_DotNet.Services;

namespace WebApp_OpenIDConnect_DotNet.Controllers
{
Expand All @@ -16,14 +17,21 @@ public HomeController()
public IActionResult Index()
{
ViewData["User"] = HttpContext.User;

// Calls method GetSessionGroupList to get groups from session.
var groups = GraphHelper.GetUserGroupsFromSession(HttpContext.Session);
if (groups?.Count > 0)
{
ViewData.Add("groupClaims", groups );
}
return View();
}

[AllowAnonymous]
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel {RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier});
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
27 changes: 7 additions & 20 deletions 5-WebApp-AuthZ/5-2-Groups/Controllers/UserProfileController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.Graph;
using Microsoft.Identity.Web;
using System.Collections.Generic;
using System.Threading.Tasks;
using WebApp_OpenIDConnect_DotNet.Services.MicrosoftGraph;
using Constants = WebApp_OpenIDConnect_DotNet.Infrastructure.Constants;

namespace WebApp_OpenIDConnect_DotNet.Controllers
Expand All @@ -13,39 +11,28 @@ namespace WebApp_OpenIDConnect_DotNet.Controllers
//[Authorize(Roles = "8873daa2-17af-4e72-973e-930c94ef7549")]
public class UserProfileController : Controller
{
private readonly ITokenAcquisition tokenAcquisition;
private readonly IMSGraphService graphService;
private readonly GraphServiceClient graphServiceClient;

public UserProfileController(ITokenAcquisition tokenAcquisition, IMSGraphService MSGraphService)
public UserProfileController(GraphServiceClient graphServiceClient)
{
this.tokenAcquisition = tokenAcquisition;
this.graphService = MSGraphService;
this.graphServiceClient= graphServiceClient;
}

[AuthorizeForScopes(Scopes = new[] { Constants.ScopeUserRead, Constants.ScopeDirectoryReadAll })]
[Authorize(Policy = "GroupAdmin")]
[AuthorizeForScopes(Scopes = new[] { Constants.ScopeUserRead })]
public async Task<IActionResult> Index()
{
// This is how group ids/names are used in the IsInRole method
// var isinrole = User.IsInRole("8873daa2-17af-4e72-973e-930c94ef7549");

string accessToken = await tokenAcquisition.GetAccessTokenForUserAsync(new[] { Constants.ScopeUserRead, Constants.ScopeDirectoryReadAll });

User me = await graphService.GetMeAsync(accessToken);
User me = await graphServiceClient.Me.Request().GetAsync();
ViewData["Me"] = me;

try
{
var photo = await graphService.GetMyPhotoAsync(accessToken);
var photo = await graphServiceClient.Me.Photo.Request().GetAsync();
ViewData["Photo"] = photo;
}
catch
{
//swallow
}

IList<Group> groups = await graphService.GetMyMemberOfGroupsAsync(accessToken);
ViewData["Groups"] = groups;

return View();
}
}
Expand Down
3 changes: 2 additions & 1 deletion 5-WebApp-AuthZ/5-2-Groups/Infrastructure/Constants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ namespace WebApp_OpenIDConnect_DotNet.Infrastructure
public static class Constants
{
public const string ScopeUserRead = "User.Read";
public const string ScopeDirectoryReadAll = "Directory.Read.All";

public const string ScopeGroupMemberRead = "GroupMember.Read.All";

public const string BearerAuthorizationScheme = "Bearer";
}
Expand Down
Loading