From 7fc031aa63e33cf75bb8276a7612b8632bd108ca Mon Sep 17 00:00:00 2001 From: Dogan Erisen Date: Wed, 19 Feb 2020 17:35:48 -0800 Subject: [PATCH 1/2] adding AppCreationScripts --- AppCreationScripts/AppCreationScripts.md | 147 ++++++++++++++++++ AppCreationScripts/Cleanup.ps1 | 70 +++++++++ AppCreationScripts/Configure.ps1 | 180 +++++++++++++++++++++++ AppCreationScripts/apps.json | 49 ++++++ AppCreationScripts/sample.json | 48 ++++++ README.md | 1 + src/app/app.module.ts | 8 +- 7 files changed, 499 insertions(+), 4 deletions(-) create mode 100644 AppCreationScripts/AppCreationScripts.md create mode 100644 AppCreationScripts/Cleanup.ps1 create mode 100644 AppCreationScripts/Configure.ps1 create mode 100644 AppCreationScripts/apps.json create mode 100644 AppCreationScripts/sample.json diff --git a/AppCreationScripts/AppCreationScripts.md b/AppCreationScripts/AppCreationScripts.md new file mode 100644 index 0000000..93a4fad --- /dev/null +++ b/AppCreationScripts/AppCreationScripts.md @@ -0,0 +1,147 @@ +# Registering the sample apps with Microsoft identity platform and updating the configuration files using PowerShell scripts + +## Overview + +### Quick summary + +1. On Windows run PowerShell 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) + +## Goal of the scripts + +### Presentation of the scripts + +This sample comes with two PowerShell scripts, which automate the creation of the Azure Active Directory applications, and the configuration of the code for this sample. Once you run them, you will only need to build the solution and you are good to test. + +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 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). + +### Usage pattern for tests and DevOps scenarios + +The `Configure.ps1` will stop if it tries to create an Azure AD application which already exists in the tenant. For this, if you are using the script to try/test the sample, or in DevOps scenarios, you might want to run `Cleanup.ps1` just before `Configure.ps1`. This is what is shown in the steps below. + +## How to use the app creation scripts ? + +### 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: + ```PowerShell + Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process + ``` +### (Optionally) install AzureAD 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: + +4. 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, + ```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 + +You're done. this just works! + +### Four 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. + +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). +- 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 indentity 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) + + 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 +- Go to **Properties** and copy the content of the **Directory Id** property +- Then use the full syntax to run the scripts: + +```PowerShell +$tenantId = "yourTenantIdGuid" +. .\Cleanup.ps1 -TenantId $tenantId +. .\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 +``` diff --git a/AppCreationScripts/Cleanup.ps1 b/AppCreationScripts/Cleanup.ps1 new file mode 100644 index 0000000..86a1e5b --- /dev/null +++ b/AppCreationScripts/Cleanup.ps1 @@ -0,0 +1,70 @@ +[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 +) + +if ($null -eq (Get-Module -ListAvailable -Name "AzureAD")) { + Install-Module "AzureAD" -Scope CurrentUser +} +Import-Module AzureAD +$ErrorActionPreference = "Stop" + +Function Cleanup +{ +<# +.Description +This function removes the Azure AD applications for the sample. These applications were created by the Configure.ps1 script +#> + + # $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 + } + else + { + if (!$TenantId) + { + $creds = Connect-AzureAD -Credential $Credential + } + else + { + $creds = Connect-AzureAD -TenantId $tenantId -Credential $Credential + } + } + + if (!$tenantId) + { + $tenantId = $creds.Tenant.Id + } + $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 "Removing 'spa' (active-directory-javascript-singlepageapp-angular) if needed" + Get-AzureADApplication -Filter "DisplayName eq 'active-directory-javascript-singlepageapp-angular'" | ForEach-Object {Remove-AzureADApplication -ObjectId $_.ObjectId } + $apps = Get-AzureADApplication -Filter "DisplayName eq 'active-directory-javascript-singlepageapp-angular'" + if ($apps) + { + Remove-AzureADApplication -ObjectId $apps.ObjectId + } + + foreach ($app in $apps) + { + Remove-AzureADApplication -ObjectId $app.ObjectId + Write-Host "Removed active-directory-javascript-singlepageapp-angular.." + } + # also remove service principals of this app + Get-AzureADServicePrincipal -filter "DisplayName eq 'active-directory-javascript-singlepageapp-angular'" | ForEach-Object {Remove-AzureADServicePrincipal -ObjectId $_.Id -Confirm:$false} + +} + +Cleanup -Credential $Credential -tenantId $TenantId \ No newline at end of file diff --git a/AppCreationScripts/Configure.ps1 b/AppCreationScripts/Configure.ps1 new file mode 100644 index 0000000..9f0f96f --- /dev/null +++ b/AppCreationScripts/Configure.ps1 @@ -0,0 +1,180 @@ +[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 +) + +<# + 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 + + There are four ways to run this script. For more information, read the AppCreationScripts.md file in the same folder as this script. +#> + +# Adds the requiredAccesses (expressed as a pipe separated string) to the requiredAccess structure +# The exposed permissions are in the $exposedPermissions collection, and the type of permission (Scope | Role) is +# described in $permissionType +Function AddResourcePermission($requiredAccess, ` + $exposedPermissions, [string]$requiredAccesses, [string]$permissionType) +{ + foreach($permission in $requiredAccesses.Trim().Split("|")) + { + 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) + } + } + } +} + +# +# Example: GetRequiredPermissions "Microsoft Graph" "Graph.Read|User.Read" +# See also: http://stackoverflow.com/questions/42164581/how-to-configure-a-new-azure-ad-application-through-powershell +Function GetRequiredPermissions([string] $applicationDisplayName, [string] $requiredDelegatedPermissions, [string]$requiredApplicationPermissions, $servicePrincipal) +{ + # If we are passed the service principal we use it directly, otherwise we find it from the display name (which might not be unique) + if ($servicePrincipal) + { + $sp = $servicePrincipal + } + else + { + $sp = Get-AzureADServicePrincipal -Filter "DisplayName eq '$applicationDisplayName'" + } + $appid = $sp.AppId + $requiredAccess = New-Object Microsoft.Open.AzureAD.Model.RequiredResourceAccess + $requiredAccess.ResourceAppId = $appid + $requiredAccess.ResourceAccess = New-Object System.Collections.Generic.List[Microsoft.Open.AzureAD.Model.ResourceAccess] + + # $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" + } + + # $sp.AppRoles | Select Id,AdminConsentDisplayName,Value: To see the list of all the Application permissions for the application + if ($requiredApplicationPermissions) + { + AddResourcePermission $requiredAccess -exposedPermissions $sp.AppRoles -requiredAccesses $requiredApplicationPermissions -permissionType "Role" + } + return $requiredAccess +} + + +Set-Content -Value "" -Path createdApps.html +Add-Content -Value "" -Path createdApps.html + +$ErrorActionPreference = "Stop" + +Function ConfigureApplications +{ +<#.Description + This function creates the Azure AD applications for the sample in the provided Azure AD tenant and updates the + configuration files in the client and service project of the visual studio solution (App.Config and Web.Config) + so that they are consistent with the Applications parameters +#> + $commonendpoint = "common" + + # $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 + } + else + { + if (!$TenantId) + { + $creds = Connect-AzureAD -Credential $Credential + } + else + { + $creds = Connect-AzureAD -TenantId $tenantId -Credential $Credential + } + } + + if (!$tenantId) + { + $tenantId = $creds.Tenant.Id + } + + $tenant = Get-AzureADTenantDetail + $tenantName = ($tenant.VerifiedDomains | Where { $_._Default -eq $True }).Name + + # Get the user running the script to add the user as the app owner + $user = Get-AzureADUser -ObjectId $creds.Account.Id + + # Create the spa AAD application + Write-Host "Creating the AAD application (active-directory-javascript-singlepageapp-angular)" + # create the application + $spaAadApplication = New-AzureADApplication -DisplayName "active-directory-javascript-singlepageapp-angular" ` + -HomePage "http://localhost:4200/" ` + -ReplyUrls "http://localhost:4200/" ` + -IdentifierUris "https://$tenantName/active-directory-javascript-singlepageapp-angular" ` + -AvailableToOtherTenants $True ` + -Oauth2AllowImplicitFlow $true ` + -PublicClient $False + + # create the service principal of the newly created application + $currentAppId = $spaAadApplication.AppId + $spaServicePrincipal = New-AzureADServicePrincipal -AppId $currentAppId -Tags {WindowsAzureActiveDirectoryIntegratedApp} + + # add the user running the script as an app owner if needed + $owner = Get-AzureADApplicationOwner -ObjectId $spaAadApplication.ObjectId + if ($owner -eq $null) + { + Add-AzureADApplicationOwner -ObjectId $spaAadApplication.ObjectId -RefObjectId $user.ObjectId + Write-Host "'$($user.UserPrincipalName)' added as an application owner to app '$($spaServicePrincipal.DisplayName)'" + } + + + Write-Host "Done creating the spa application (active-directory-javascript-singlepageapp-angular)" + + # URL of the AAD application in the Azure portal + # Future? $spaPortalUrl = "https://portal.azure.com/#@"+$tenantName+"/blade/Microsoft_AAD_RegisteredApps/ApplicationMenuBlade/Overview/appId/"+$spaAadApplication.AppId+"/objectId/"+$spaAadApplication.ObjectId+"/isMSAApp/" + $spaPortalUrl = "https://portal.azure.com/#blade/Microsoft_AAD_RegisteredApps/ApplicationMenuBlade/CallAnAPI/appId/"+$spaAadApplication.AppId+"/objectId/"+$spaAadApplication.ObjectId+"/isMSAApp/" + Add-Content -Value "" -Path createdApps.html + + $requiredResourcesAccess = New-Object System.Collections.Generic.List[Microsoft.Open.AzureAD.Model.RequiredResourceAccess] + + # Add Required Resources Access (from 'spa' to 'Microsoft Graph') + Write-Host "Getting access from 'spa' to 'Microsoft Graph'" + $requiredPermissions = GetRequiredPermissions -applicationDisplayName "Microsoft Graph" ` + -requiredDelegatedPermissions "User.Read" ` + + $requiredResourcesAccess.Add($requiredPermissions) + + + Set-AzureADApplication -ObjectId $spaAadApplication.ObjectId -RequiredResourceAccess $requiredResourcesAccess + Write-Host "Granted permissions." + + # Update config file for 'spa' + $configFile = $pwd.Path + "\..\src\app\app.module.ts" + Write-Host "Updating the sample code ($configFile)" + + Add-Content -Value "
ApplicationAppIdUrl in the Azure portal
spa$currentAppIdactive-directory-javascript-singlepageapp-angular
" -Path createdApps.html +} + +# Pre-requisites +if ((Get-Module -ListAvailable -Name "AzureAD") -eq $null) { + Install-Module "AzureAD" -Scope CurrentUser +} + +Import-Module AzureAD + +# Run interactively (will ask you for the tenant ID) +ConfigureApplications -Credential $Credential -tenantId $TenantId \ No newline at end of file diff --git a/AppCreationScripts/apps.json b/AppCreationScripts/apps.json new file mode 100644 index 0000000..003e754 --- /dev/null +++ b/AppCreationScripts/apps.json @@ -0,0 +1,49 @@ +{ + "Sample": { + "Title": "A simple Angular single page application calling the Microsoft Graph using MSAL Angular (Azure AD V2 endpoint)", + "Level": 100, + "Client": "SinglePageApplication" + }, + "AppRegistrations": [ + { + "x-ms-id": "AngularSpa", + "x-ms-name": "active-directory-javascript-singlepageapp-angular", + "x-ms-version": "2.0", + "logoutUrl": "http://localhost:4200/", + "replyUrlsWithType": [ + { + "url": "http://localhost:4200/", + "type": "Web" + } + ], + "oauth2AllowImplicitFlow": true, + "oauth2AllowIdTokenImplicitFlow": true, + "requiredResourceAccess": [ + { + "x-ms-resourceAppName": "Microsoft Graph", + "resourceAppId": "00000003-0000-0000-c000-000000000000", + "resourceAccess": [ + { + "id": "e1fe6dd8-ba31-4d61-89e7-88639da4683d", + "type": "Scope", + "x-ms-name": "user.read" + } + ] + } + ], + "codeConfigurations": [ + { + "settingFile": "/src/app/app.module.ts", + "replaceTokens": + { + "appId": "Enter_the_Application_Id_Here", + "tenantId": "Enter_the_Tenant_Info_Here", + "authorityEndpointHost": "Enter_the_Cloud_Instance_Id_Here", + "redirectUri": "Enter_the_Redirect_Uri_Here", + "msgraphEndpointHost": "Enter_the_Graph_Endpoint_Here" + } + } + ] + } + ] + } \ No newline at end of file diff --git a/AppCreationScripts/sample.json b/AppCreationScripts/sample.json new file mode 100644 index 0000000..23274a4 --- /dev/null +++ b/AppCreationScripts/sample.json @@ -0,0 +1,48 @@ +{ + "Sample": { + "Title": "A simple Angular single page application calling the Microsoft Graph using MSAL Angular (Azure AD V2 endpoint)", + "Level": 100, + "Client": "SinglePageApplication", + "Service": "Microsoft Graph", + "RepositoryUrl": "active-directory-javascript-singlepageapp-angular", + "Endpoint": "AAD v2.0" + }, + + "AADApps": [ + { + "Id": "spa", + "Name": "active-directory-javascript-singlepageapp-angular", + "Kind" : "SinglePageApplication", + "HomePage": "http://localhost:4200/", + "ReplyUrls":"http://localhost:4200/", + "RequiredResourcesAccess": [ + { + "Resource": "Microsoft Graph", + "DelegatedPermissions": [ "User.Read" ] + } + ] + } + ], + + "CodeConfiguration": [ + { + "App": "spa", + "SettingKind": "TypeScript", + "SettingFile": "\\..\\src\\app\\app.module.ts", + "Mappings": [ + { + "key": "clientId", + "value": ".AppId" + }, + { + "key": "authority", + "value": "\"https://login.microsoftonline.com/\"+$tenantName" + }, + { + "key": "redirectUri", + "value": ".HomePage" + } + ] + } + ] + } \ No newline at end of file diff --git a/README.md b/README.md index 13fac19..7d82e00 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,7 @@ A simple Angular single-page application which demonstrates how to configure [MS | File/folder | Description | |-------------------|--------------------------------------------| +| `AppCreationScripts` | Contains automation scripts for Powershell users (can be safely removed if desired). | | `e2e` | End-to-end test files. | | `src` | Sample source code. | | `.editorconfig` | Defines editor config settings. | diff --git a/src/app/app.module.ts b/src/app/app.module.ts index f0cce8e..e47294c 100644 --- a/src/app/app.module.ts +++ b/src/app/app.module.ts @@ -31,9 +31,9 @@ const isIE = window.navigator.userAgent.indexOf('MSIE ') > -1 || window.navigato AppRoutingModule, MsalModule.forRoot({ auth: { - clientId: 'Enter_the_Application_Id_here', // This is your client ID - authority: 'https://login.microsoftonline.com/Enter_the_Tenant_Info_Here', // This is your tenant info - redirectUri: 'Enter_the_Redirect_Uri_Here' // This is your redirect URI + clientId: 'Enter_the_Application_Id_Here', + authority: 'Enter_the_Cloud_Instance_Id_HereEnter_the_Tenant_Info_Here', + redirectUri: 'Enter_the_Redirect_Uri_Here', }, cache: { cacheLocation: 'localStorage', @@ -49,7 +49,7 @@ const isIE = window.navigator.userAgent.indexOf('MSIE ') > -1 || window.navigato ], unprotectedResources: [], protectedResourceMap: [ - ['https://graph.microsoft.com/v1.0/me', ['user.read']] + ['Enter_the_Graph_Endpoint_Herev1.0/me', ['user.read']] ], extraQueryParameters: {} }) From 31f4267fcf724ec62d4641c4e3e2da70b59e25fd Mon Sep 17 00:00:00 2001 From: Dogan Erisen Date: Thu, 20 Feb 2020 16:38:46 -0800 Subject: [PATCH 2/2] fixing grammar --- AppCreationScripts/AppCreationScripts.md | 94 +++++++++++++----------- 1 file changed, 51 insertions(+), 43 deletions(-) diff --git a/AppCreationScripts/AppCreationScripts.md b/AppCreationScripts/AppCreationScripts.md index 93a4fad..5f7863c 100644 --- a/AppCreationScripts/AppCreationScripts.md +++ b/AppCreationScripts/AppCreationScripts.md @@ -2,31 +2,39 @@ ## Overview + - [Quick summary](#quick-summary) + - [Goal of the scripts](#goal-of-the-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) + - [(Optionally) install AzureAD PowerShell modules](#optionally-install-azuread-powershell-modules) + - [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) + ### Quick summary -1. On Windows run PowerShell and navigate to the root of the cloned directory -1. In PowerShell run: +1. On Windows run PowerShell and navigate to the root of the cloned directory. +2. 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) + +3. Run the script to create your Azure AD application and configure the code of the sample application accordingly: + ```PowerShell cd .\AppCreationScripts\ .\Configure.ps1 ``` -1. Open the Visual Studio solution and click start -### More details +4. Open the Visual Studio solution and click start. -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) +> **NOTE** Other ways of running the scripts are described below ## Goal of the scripts @@ -36,68 +44,67 @@ 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 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). +- `Configure.ps1`, which creates Azure AD applications and their related objects (permissions, dependencies, secrets), and changes the configuration files in the C# and JavaScript projects. -- `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 The `Configure.ps1` will stop if it tries to create an Azure AD application which already exists in the tenant. For this, if you are using the script to try/test the sample, or in DevOps scenarios, you might want to run `Cleanup.ps1` just before `Configure.ps1`. This is what is shown in the steps below. -## How to use the app creation scripts ? +## How to use the app creation scripts ### 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: + ```PowerShell Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process ``` + ### (Optionally) install AzureAD 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: 4. 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, +5. 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 -You're done. this just works! +You're done. This just works! ### Four 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. - -Here are the details on how to do this. +- Interactive: you will be prompted for credentials, and the scripts decides 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 the tenant in which you want to create the objects and credentials, and the scripts will create the objects. #### Option 1 (interactive) @@ -108,30 +115,31 @@ Note that the script will choose the tenant in which to create the applications, #### Option 2 (non-interactive) -When you know the indentity 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 +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 +..\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. +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) 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 -- Go to **Properties** and copy the content of the **Directory Id** property + +- 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. - Then use the full syntax to run the scripts: ```PowerShell $tenantId = "yourTenantIdGuid" -. .\Cleanup.ps1 -TenantId $tenantId -. .\Configure.ps1 -TenantId $tenantId +..\Cleanup.ps1 -TenantId $tenantId +..\Configure.ps1 -TenantId $tenantId ``` #### Option 4 (non-interactive, and create apps in a specified tenant) @@ -142,6 +150,6 @@ This option combines option 2 and option 3: it creates the application in a spec $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 +..\Cleanup.ps1 -Credential $mycreds -TenantId $tenantId +..\Configure.ps1 -Credential $mycreds -TenantId $tenantId ```