diff --git a/.gitignore b/.gitignore index dfcfd56..2553e8d 100644 --- a/.gitignore +++ b/.gitignore @@ -348,3 +348,6 @@ MigrationBackup/ # Ionide (cross platform F# VS Code tools) working folder .ionide/ +/TodoListClient/Properties/ServiceDependencies/CAAuthNContextAppDemo - Web Deploy +/TodoListClient/Properties/serviceDependencies.CAAuthNContextAppDemo - Web Deploy.json +/AppCreationScripts/createdApps.html diff --git a/AppCreationScripts/AppCreationScripts.md b/AppCreationScripts/AppCreationScripts.md index 7512ab4..6e60a27 100644 --- a/AppCreationScripts/AppCreationScripts.md +++ b/AppCreationScripts/AppCreationScripts.md @@ -1,45 +1,35 @@ -# Registering the sample apps with the Microsoft identity platform and updating the configuration files using PowerShell +# Registering sample apps with the Microsoft identity platform and updating configuration files using PowerShell ## Overview ### Quick summary -1. On Windows run PowerShell as **Administrator** 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) +1. Run the script to create your Azure AD application and configure the code of the sample application accordingly. ```PowerShell cd .\AppCreationScripts\ - .\Configure.ps1 + .\Configure.ps1 -TenantId "your test tenant's id" -AzureEnvironmentName "[Optional] - Azure environment, defaults to 'Global'" ``` -1. Open the Visual Studio solution and click start - ### More details -The following paragraphs: - -- [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](#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 (Interactive, but create apps in a specified tenant)](#option-3-Interactive-but-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 @@ -50,14 +40,14 @@ This sample comes with two PowerShell scripts, which automate the creation of th These scripts are: - `Configure.ps1` which: - - creates Azure AD applications and their related objects (permissions, dependencies, secrets), - - changes the configuration files in the C# and JavaScript projects. + - creates Azure AD applications and their related objects (permissions, dependencies, secrets, app roles), + - changes the configuration files in the sample projects. - creates a summary file named `createdApps.html` in the folder from which you ran the script, and containing, for each Azure AD application it created: - the identifier of the application - the AppId of the application - the url of its registration in the [Azure portal](https://portal.azure.com). -- `Cleanup.ps1` which cleans-up the Azure AD objects created by `Configure.ps1`. Note that this script does not revert the changes done in the configuration files, though. You will need to undo the change from source control (from Visual Studio, or from the command line using, for instance, git reset). +- `Cleanup.ps1` which cleans-up the Azure AD objects created by `Configure.ps1`. Note that this script does not revert the changes done in the configuration files, though. You will need to undo the change from source control (from Visual Studio, or from the command line using, for instance, `git reset`). ### Usage pattern for tests and DevOps scenarios @@ -75,23 +65,23 @@ The `Configure.ps1` will stop if it tries to create an Azure AD application whic Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process ``` -### (Optionally) install AzureAD PowerShell modules +### (Optionally) install Microsoft.Graph.Applications PowerShell modules -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: +The scripts install the required PowerShell module (Microsoft.Graph.Applications) 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: -1. 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 Microsoft.Graph.Applications 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). + 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 + Install-Module Microsoft.Graph.Applications ``` or if you cannot be administrator on your machine, run: - + ```PowerShell - Install-Module AzureAD -Scope CurrentUser + Install-Module Microsoft.Graph.Applications -Scope CurrentUser ``` ### Run the script and start running @@ -106,44 +96,29 @@ The scripts install the required PowerShell module (AzureAD) for the current use 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! +You're done! -### Four ways to run the script +### Two ways to run the script We advise four ways of running the script: - Interactive: you will be prompted for credentials, and the scripts decide in which tenant to create the objects, -- non-interactive: you will provide credentials, and the scripts decide in which tenant to create the objects, -- Interactive in specific tenant: you will provide the tenant in which you want to create the objects and then you will be prompted for credentials, and the scripts will create the objects, -- non-interactive in specific tenant: you will provide tenant in which you want to create the objects and credentials, and the scripts will create the objects. +- Interactive in specific tenant: you will provide the tenant in which you want to create the objects and then you will be prompted for credentials, and the scripts will create the objects, Here are the details on how to do this. #### Option 1 (interactive) -- Just run ``. .\Configure.ps1``, and you will be prompted to sign-in (email address, password, and if needed MFA). +- Just run ``.\Configure.ps1``, and you will be prompted to sign-in (email address, password, and if needed MFA). - The script will be run as the signed-in user and will use the tenant in which the user is defined. Note that the script will choose the tenant in which to create the applications, based on the user. Also to run the `Cleanup.ps1` script, you will need to re-sign-in. -#### Option 2 (non-interactive) - -When you know the identity and credentials of the user in the name of whom you want to create the applications, you can use the non-interactive approach. It's more adapted to DevOps. Here is an example of script you'd want to run in a PowerShell Window - -```PowerShell -$secpasswd = ConvertTo-SecureString "[Password here]" -AsPlainText -Force -$mycreds = New-Object System.Management.Automation.PSCredential ("[login@tenantName here]", $secpasswd) -. .\Cleanup.ps1 -Credential $mycreds -. .\Configure.ps1 -Credential $mycreds -``` - -Of course, in real life, you might already get the password as a `SecureString`. You might also want to get the password from KeyVault. - -#### Option 3 (Interactive, but create apps in a specified tenant) +#### Option 2 (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) +- 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 - Go to **Properties** and copy the content of the **Directory Id** property @@ -155,21 +130,9 @@ $tenantId = "yourTenantIdGuid" . .\Configure.ps1 -TenantId $tenantId ``` -#### Option 4 (non-interactive, and create apps in a specified tenant) - -This option combines option 2 and option 3: it creates the application in a specific tenant. See option 3 for the way to get the tenant Id. Then run: - -```PowerShell -$secpasswd = ConvertTo-SecureString "[Password here]" -AsPlainText -Force -$mycreds = New-Object System.Management.Automation.PSCredential ("[login@tenantName here]", $secpasswd) -$tenantId = "yourTenantIdGuid" -. .\Cleanup.ps1 -Credential $mycreds -TenantId $tenantId -. .\Configure.ps1 -Credential $mycreds -TenantId $tenantId -``` - ### Running the script on Azure Sovereign clouds -All the four options listed above, can be used on any Azure Sovereign clouds. By default, the script targets `AzureCloud`, but it can be changed using the parameter `-AzureEnvironmentName`. +All the four options listed above can be used on any Azure Sovereign clouds. By default, the script targets `AzureCloud`, but it can be changed using the parameter `-AzureEnvironmentName`. The acceptable values for this parameter are: diff --git a/AppCreationScripts/Cleanup.ps1 b/AppCreationScripts/Cleanup.ps1 index 25adc2a..334888f 100644 --- a/AppCreationScripts/Cleanup.ps1 +++ b/AppCreationScripts/Cleanup.ps1 @@ -1,26 +1,17 @@ + [CmdletBinding()] param( - [PSCredential] $Credential, [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')] [string] $tenantId, - [Parameter(Mandatory=$False, HelpMessage='Azure environment to use while running the script (it defaults to AzureCloud)')] + [Parameter(Mandatory=$False, HelpMessage='Azure environment to use while running the script. Default = Global')] [string] $azureEnvironmentName ) -#Requires -Modules AzureAD -RunAsAdministrator - - -if ($null -eq (Get-Module -ListAvailable -Name "AzureAD")) { - Install-Module "AzureAD" -Scope CurrentUser -} -Import-Module AzureAD -$ErrorActionPreference = "Stop" - Function Cleanup { if (!$azureEnvironmentName) { - $azureEnvironmentName = "AzureCloud" + $azureEnvironmentName = "Global" } <# @@ -31,63 +22,63 @@ Function Cleanup # $tenantId is the Active Directory Tenant. This is a GUID which represents the "Directory ID" of the AzureAD tenant # into which you want to create the apps. Look it up in the Azure portal in the "Properties" of the Azure AD. - # Login to Azure PowerShell (interactive if credentials are not already provided: - # you'll need to sign-in with creds enabling your to create apps in the tenant) - if (!$Credential -and $TenantId) - { - $creds = Connect-AzureAD -TenantId $tenantId -AzureEnvironmentName $azureEnvironmentName + # Connect to the Microsoft Graph API + Write-Host "Connecting to Microsoft Graph" + if ($tenantId -eq "") { + Connect-MgGraph -Scopes "Application.ReadWrite.All" -Environment $azureEnvironmentName + $tenantId = (Get-MgContext).TenantId } - else - { - if (!$TenantId) - { - $creds = Connect-AzureAD -Credential $Credential -AzureEnvironmentName $azureEnvironmentName - } - else - { - $creds = Connect-AzureAD -TenantId $tenantId -Credential $Credential -AzureEnvironmentName $azureEnvironmentName - } - } - - if (!$tenantId) - { - $tenantId = $creds.Tenant.Id + else { + Connect-MgGraph -TenantId $tenantId -Scopes "Application.ReadWrite.All" -Environment $azureEnvironmentName } - $tenant = Get-AzureADTenantDetail - $tenantName = ($tenant.VerifiedDomains | Where-Object { $_._Default -eq $True }).Name # Removes the applications - Write-Host "Cleaning-up applications from tenant '$tenantName'" + Write-Host "Cleaning-up applications from tenant '$tenantId'" Write-Host "Removing 'client' (TodoListClient-authContext-webapp) if needed" try { - Get-AzureADApplication -Filter "DisplayName eq 'TodoListClient-authContext-webapp'" | ForEach-Object {Remove-AzureADApplication -ObjectId $_.ObjectId } + Get-MgApplication -Filter "DisplayName eq 'TodoListClient-authContext-webapp'" | ForEach-Object {Remove-MgApplication -ApplicationId $_.Id } } catch { - Write-Host "Unable to remove the 'TodoListClient-authContext-webapp' . Try deleting manually." -ForegroundColor White -BackgroundColor Red + Write-Host "Unable to remove the application 'TodoListClient-authContext-webapp' . Try deleting manually." -ForegroundColor White -BackgroundColor Red } - $apps = Get-AzureADApplication -Filter "DisplayName eq 'TodoListClient-authContext-webapp'" + + Write-Host "Making sure there are no more (TodoListClient-authContext-webapp) applications found, will remove if needed..." + $apps = Get-MgApplication -Filter "DisplayName eq 'TodoListClient-authContext-webapp'" + if ($apps) { - Remove-AzureADApplication -ObjectId $apps.ObjectId + Remove-MgApplication -ApplicationId $apps.Id } foreach ($app in $apps) { - Remove-AzureADApplication -ObjectId $app.ObjectId + Remove-MgApplication -ApplicationId $app.Id Write-Host "Removed TodoListClient-authContext-webapp.." } + # also remove service principals of this app try { - Get-AzureADServicePrincipal -filter "DisplayName eq 'TodoListClient-authContext-webapp'" | ForEach-Object {Remove-AzureADServicePrincipal -ObjectId $_.Id -Confirm:$false} + Get-MgServicePrincipal -filter "DisplayName eq 'TodoListClient-authContext-webapp'" | ForEach-Object {Remove-MgServicePrincipal -ApplicationId $_.Id -Confirm:$false} } catch { - Write-Host "Unable to remove ServicePrincipal 'TodoListClient-authContext-webapp' . Try deleting manually from Enterprise applications." -ForegroundColor White -BackgroundColor Red + Write-Host "Unable to remove ServicePrincipal 'TodoListClient-authContext-webapp' . Try deleting manually from Enterprise applications." -ForegroundColor White -BackgroundColor Red } } -Cleanup -Credential $Credential -tenantId $TenantId \ No newline at end of file +if ($null -eq (Get-Module -ListAvailable -Name "Microsoft.Graph.Applications")) { + Install-Module "Microsoft.Graph.Applications" -Scope CurrentUser +} +Import-Module Microsoft.Graph.Applications +$ErrorActionPreference = "Stop" + + +Cleanup -tenantId $tenantId -environment $azureEnvironmentName + +Write-Host "Disconnecting from tenant" +Disconnect-MgGraph + diff --git a/AppCreationScripts/Configure.ps1 b/AppCreationScripts/Configure.ps1 index 11887f7..5bb5380 100644 --- a/AppCreationScripts/Configure.ps1 +++ b/AppCreationScripts/Configure.ps1 @@ -1,49 +1,32 @@ + [CmdletBinding()] param( - [PSCredential] $Credential, [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')] [string] $tenantId, - [Parameter(Mandatory=$False, HelpMessage='Azure environment to use while running the script (it defaults to AzureCloud)')] + [Parameter(Mandatory=$False, HelpMessage='Azure environment to use while running the script. Default = Global')] [string] $azureEnvironmentName ) -#Requires -Modules AzureAD -RunAsAdministrator - <# This script creates the Azure AD applications needed for this sample and updates the configuration files for the visual Studio projects from the data in the Azure AD applications. - Before running this script you need to install the AzureAD cmdlets as an administrator. - For this: - 1) Run Powershell as an administrator - 2) in the PowerShell window, type: Install-Module AzureAD - + In case you don't have Microsoft.Graph.Applications already installed, the script will automatically install it for the current user + There are four ways to run this script. For more information, read the AppCreationScripts.md file in the same folder as this script. #> -# Create a password that can be used as an application key -Function ComputePassword -{ - $aesManaged = New-Object "System.Security.Cryptography.AesManaged" - $aesManaged.Mode = [System.Security.Cryptography.CipherMode]::CBC - $aesManaged.Padding = [System.Security.Cryptography.PaddingMode]::Zeros - $aesManaged.BlockSize = 128 - $aesManaged.KeySize = 256 - $aesManaged.GenerateKey() - return [System.Convert]::ToBase64String($aesManaged.Key) -} - # Create an application key # See https://www.sabin.io/blog/adding-an-azure-active-directory-application-and-key-using-powershell/ -Function CreateAppKey([DateTime] $fromDate, [double] $durationInYears, [string]$pw) +Function CreateAppKey([DateTime] $fromDate, [double] $durationInMonths) { - $endDate = $fromDate.AddYears($durationInYears) - $keyId = (New-Guid).ToString(); - $key = New-Object Microsoft.Open.AzureAD.Model.PasswordCredential - $key.StartDate = $fromDate - $key.EndDate = $endDate - $key.Value = $pw - $key.KeyId = $keyId + $key = New-Object Microsoft.Graph.PowerShell.Models.MicrosoftGraphPasswordCredential + + $key.StartDateTime = $fromDate + $key.EndDateTime = $fromDate.AddMonths($durationInMonths) + $key.KeyId = (New-Guid).ToString() + $key.DisplayName = "app secret" + return $key } @@ -53,19 +36,19 @@ Function CreateAppKey([DateTime] $fromDate, [double] $durationInYears, [string]$ Function AddResourcePermission($requiredAccess, ` $exposedPermissions, [string]$requiredAccesses, [string]$permissionType) { - foreach($permission in $requiredAccesses.Trim().Split("|")) + foreach($permission in $requiredAccesses.Trim().Split("|")) + { + foreach($exposedPermission in $exposedPermissions) { - foreach($exposedPermission in $exposedPermissions) - { - if ($exposedPermission.Value -eq $permission) - { - $resourceAccess = New-Object Microsoft.Open.AzureAD.Model.ResourceAccess - $resourceAccess.Type = $permissionType # Scope = Delegated permissions | Role = Application permissions - $resourceAccess.Id = $exposedPermission.Id # Read directory data - $requiredAccess.ResourceAccess.Add($resourceAccess) - } - } + if ($exposedPermission.Value -eq $permission) + { + $resourceAccess = New-Object Microsoft.Graph.PowerShell.Models.MicrosoftGraphResourceAccess + $resourceAccess.Type = $permissionType # Scope = Delegated permissions | Role = Application permissions + $resourceAccess.Id = $exposedPermission.Id # Read directory data + $requiredAccess.ResourceAccess += $resourceAccess + } } + } } # @@ -80,17 +63,17 @@ Function GetRequiredPermissions([string] $applicationDisplayName, [string] $requ } else { - $sp = Get-AzureADServicePrincipal -Filter "DisplayName eq '$applicationDisplayName'" + $sp = Get-MgServicePrincipal -Filter "DisplayName eq '$applicationDisplayName'" } $appid = $sp.AppId - $requiredAccess = New-Object Microsoft.Open.AzureAD.Model.RequiredResourceAccess + $requiredAccess = New-Object Microsoft.Graph.PowerShell.Models.MicrosoftGraphRequiredResourceAccess $requiredAccess.ResourceAppId = $appid - $requiredAccess.ResourceAccess = New-Object System.Collections.Generic.List[Microsoft.Open.AzureAD.Model.ResourceAccess] + $requiredAccess.ResourceAccess = New-Object System.Collections.Generic.List[Microsoft.Graph.PowerShell.Models.MicrosoftGraphResourceAccess] # $sp.Oauth2Permissions | Select Id,AdminConsentDisplayName,Value: To see the list of all the Delegated permissions for the application: if ($requiredDelegatedPermissions) { - AddResourcePermission $requiredAccess -exposedPermissions $sp.Oauth2Permissions -requiredAccesses $requiredDelegatedPermissions -permissionType "Scope" + AddResourcePermission $requiredAccess -exposedPermissions $sp.Oauth2PermissionScopes -requiredAccesses $requiredDelegatedPermissions -permissionType "Scope" } # $sp.AppRoles | Select Id,AdminConsentDisplayName,Value: To see the list of all the Application permissions for the application @@ -104,16 +87,14 @@ Function GetRequiredPermissions([string] $applicationDisplayName, [string] $requ Function UpdateLine([string] $line, [string] $value) { - $index = $line.IndexOf('=') - $delimiter = ';' - if ($index -eq -1) - { - $index = $line.IndexOf(':') - $delimiter = ',' - } + $index = $line.IndexOf(':') + $lineEnd = '' + + if($line[$line.Length - 1] -eq ','){ $lineEnd = ',' } + if ($index -ige 0) { - $line = $line.Substring(0, $index+1) + " "+'"'+$value+'"'+$delimiter + $line = $line.Substring(0, $index+1) + " " + '"' + $value+ '"' + $lineEnd } return $line } @@ -138,137 +119,121 @@ Function UpdateTextFile([string] $configFilePath, [System.Collections.HashTable] Set-Content -Path $configFilePath -Value $lines -Force } -Set-Content -Value "
Application | AppId | Url in the Azure portal |
---|---|---|
client | $currentAppId | TodoListClient-authContext-webapp |
client | $currentAppId | TodoListClient-authContext-webapp |