diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json
new file mode 100644
index 0000000..8aafaa7
--- /dev/null
+++ b/.devcontainer/devcontainer.json
@@ -0,0 +1,54 @@
+// For format details, see https://aka.ms/devcontainer.json. For config options, see the
+// README at: https://github.com/devcontainers/templates/tree/main/src/docker-existing-dockerfile
+{
+ "name": "Existing Dockerfile",
+ "build": {
+ // Sets the run context to one level up instead of the .devcontainer folder.
+ "context": "..",
+ // Update the 'dockerFile' property if you aren't using the standard 'Dockerfile' filename.
+ "dockerfile": "../Dockerfile"
+ }
+ // "features": {
+ // "ghcr.io/guiyomh/features/vim:0": {},
+ // "ghcr.io/devcontainers-community/npm-features/prettier:1": {
+ // "version": "latest"
+ // },
+ // "ghcr.io/jayree/devcontainer-features/npm-registry:1": {
+ // "registry": "@SCOPE:registry=https://npm.pkg.github.com\n//npm.pkg.github.com/:_authToken=${localEnv:GITHUB_TOKEN}"
+ // },
+ // "ghcr.io/bdsoha/devcontainers/custom-root-ca:1": {
+ // "bundle": true,
+ // "verify": true,
+ // "source": "https://netfree.link/cacert/isp/018/ca.crt"
+ // }
+ // }
+
+ // Features to add to the dev container. More info: https://containers.dev/features.
+ // "features": {},
+
+ // Use 'forwardPorts' to make a list of ports inside the container available locally.
+ // "forwardPorts": [],
+
+ // Uncomment the next line to run commands after the container is created.
+ // "postCreateCommand": "cat /etc/os-release",
+ // "postCreateCommand": "npm install -g @devcontainers/cli",
+ // "postCreateCommand": "npm install",
+
+ // Configure tool-specific properties.
+ // "customizations": {},
+ // "customizations": {
+ // "vscode": {
+ // "extensions": [
+ // "mads-hartmann.bash-ide-vscode",
+ // "dbaeumer.vscode-eslint",
+ // "editorconfig.editorconfig"
+ // ]
+ // }
+ // }
+
+ // Uncomment to connect as an existing user other than the container default. More info: https://aka.ms/dev-containers-non-root.
+ // "remoteUser": "devcontainer"
+
+
+
+}
diff --git a/App/Collabor8.png b/App/Collabor8.png
new file mode 100644
index 0000000..8cb7eb4
Binary files /dev/null and b/App/Collabor8.png differ
diff --git a/App/Site-logo.svg b/App/Site-logo.svg
new file mode 100644
index 0000000..a122e63
--- /dev/null
+++ b/App/Site-logo.svg
@@ -0,0 +1,24 @@
+
diff --git a/App/authConfig.js b/App/authConfig.js
new file mode 100644
index 0000000..39bf539
--- /dev/null
+++ b/App/authConfig.js
@@ -0,0 +1,69 @@
+/**
+ * Configuration object to be passed to MSAL instance on creation.
+ * For a full list of MSAL.js configuration parameters, visit:
+ * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/configuration.md
+ */
+
+const msalConfig = {
+ auth: {
+ clientId: 'b954d729-c75e-418d-b2e4-1dd38ac8e865', // This is the ONLY mandatory field that you need to supply.
+ authority: 'https://login.microsoftonline.com/4d1df598-ac19-4734-86f0-8a645992dfa1', // Defaults to "https://login.microsoftonline.com/common"
+ redirectUri: 'https://it75-web-c8a-sampleapp-dev.azurewebsites.net/', // You must register this URI on Azure Portal/App Registration. Defaults to window.location.href e.g. http://localhost:3000/
+ navigateToLoginRequestUrl: true, // If "true", will navigate back to the original request location before processing the auth code response.
+ },
+ cache: {
+ cacheLocation: 'sessionStorage', // Configures cache location. "sessionStorage" is more secure, but "localStorage" gives you SSO.
+ storeAuthStateInCookie: false, // set this to true if you have to support IE
+ },
+ system: {
+ loggerOptions: {
+ loggerCallback: (level, message, containsPii) => {
+ if (containsPii) {
+ return;
+ }
+ switch (level) {
+ case msal.LogLevel.Error:
+ console.error(message);
+ return;
+ case msal.LogLevel.Info:
+ console.info(message);
+ return;
+ case msal.LogLevel.Verbose:
+ console.debug(message);
+ return;
+ case msal.LogLevel.Warning:
+ console.warn(message);
+ return;
+ }
+ },
+ },
+ },
+};
+
+/**
+ * Scopes you add here will be prompted for user consent during sign-in.
+ * By default, MSAL.js will add OIDC scopes (openid, profile, email) to any login request.
+ * For more information about OIDC scopes, visit:
+ * https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent#openid-connect-scopes
+ */
+const loginRequest = {
+ scopes: ["openid", "profile"],
+};
+
+/**
+ * An optional silentRequest object can be used to achieve silent SSO
+ * between applications by providing a "login_hint" property.
+ */
+
+// const silentRequest = {
+// scopes: ["openid", "profile"],
+// loginHint: "example@domain.net"
+// };
+
+// exporting config object for jest
+if (typeof exports !== 'undefined') {
+ module.exports = {
+ msalConfig: msalConfig,
+ loginRequest: loginRequest,
+ };
+}
\ No newline at end of file
diff --git a/App/authPopup.js b/App/authPopup.js
new file mode 100644
index 0000000..9394f7c
--- /dev/null
+++ b/App/authPopup.js
@@ -0,0 +1,97 @@
+// Create the main myMSALObj instance
+// configuration parameters are located at authConfig.js
+const myMSALObj = new msal.PublicClientApplication(msalConfig);
+
+let username = "";
+
+function selectAccount () {
+
+ /**
+ * See here for more info on account retrieval:
+ * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-common/docs/Accounts.md
+ */
+
+ const currentAccounts = myMSALObj.getAllAccounts();
+
+ if (!currentAccounts || currentAccounts.length < 1) {
+ return;
+ } else if (currentAccounts.length > 1) {
+ // Add your account choosing logic here
+ console.warn("Multiple accounts detected.");
+ } else if (currentAccounts.length === 1) {
+ username = currentAccounts[0].username;
+ welcomeUser(username);
+ updateTable();
+ }
+}
+
+function handleResponse(response) {
+
+ /**
+ * To see the full list of response object properties, visit:
+ * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/request-response-object.md#response
+ */
+
+ if (response !== null) {
+ username = response.account.username;
+ welcomeUser(username);
+ updateTable();
+ UserDiv.innerHTML = `Welcome ${username}`;
+ TokenDiv.innerHTML = `Access token: ${response.accessToken}`;
+ } else {
+
+ selectAccount();
+
+ /**
+ * If you already have a session that exists with the authentication server, you can use the ssoSilent() API
+ * to make request for tokens without interaction, by providing a "login_hint" property. To try this, comment the
+ * line above and uncomment the section below.
+ */
+
+ // myMSALObj.ssoSilent(silentRequest).
+ // then(() => {
+ // const currentAccounts = myMSALObj.getAllAccounts();
+ // username = currentAccounts[0].username;
+ // welcomeUser(username);
+ // updateTable();
+ // }).catch(error => {
+ // console.error("Silent Error: " + error);
+ // if (error instanceof msal.InteractionRequiredAuthError) {
+ // signIn();
+ // }
+ // });
+ }
+}
+
+function signIn() {
+
+ /**
+ * You can pass a custom request object below. This will override the initial configuration. For more information, visit:
+ * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/request-response-object.md#request
+ */
+
+ myMSALObj.loginPopup(loginRequest)
+ .then(handleResponse)
+ .catch(error => {
+ console.error(error);
+ });
+}
+
+function signOut() {
+
+ /**
+ * You can pass a custom request object below. This will override the initial configuration. For more information, visit:
+ * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/request-response-object.md#request
+ */
+
+ // Choose which account to logout from by passing a username.
+ const logoutRequest = {
+ account: myMSALObj.getAccountByUsername(username),
+ mainWindowRedirectUri: 'http://localhost:3000/signout',
+ redirectUri: 'http://localhost:3000/redirect.html',
+ };
+
+ myMSALObj.logoutPopup(logoutRequest);
+}
+
+selectAccount();
diff --git a/App/authRedirect.js b/App/authRedirect.js
new file mode 100644
index 0000000..e1ec389
--- /dev/null
+++ b/App/authRedirect.js
@@ -0,0 +1,100 @@
+// Create the main myMSALObj instance
+// configuration parameters are located at authConfig.js
+const myMSALObj = new msal.PublicClientApplication(msalConfig);
+
+let username = "";
+
+/**
+ * A promise handler needs to be registered for handling the
+ * response returned from redirect flow. For more information, visit:
+ *
+ */
+myMSALObj.handleRedirectPromise()
+ .then(handleResponse)
+ .catch((error) => {
+ console.error(error);
+ });
+
+function selectAccount () {
+
+ /**
+ * See here for more info on account retrieval:
+ * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-common/docs/Accounts.md
+ */
+
+ const currentAccounts = myMSALObj.getAllAccounts();
+
+ if (!currentAccounts) {
+ return;
+ } else if (currentAccounts.length > 1) {
+ // Add your account choosing logic here
+ console.warn("Multiple accounts detected.");
+ } else if (currentAccounts.length === 1) {
+ username = currentAccounts[0].username;
+ welcomeUser(username);
+ updateTable();
+ }
+}
+
+function handleResponse(response) {
+
+ /**
+ * To see the full list of response object properties, visit:
+ * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/request-response-object.md#response
+ */
+
+ if (response !== null) {
+ username = response.account.username;
+ welcomeUser(username);
+ updateTable();
+ } else {
+
+ selectAccount();
+
+ /**
+ * If you already have a session that exists with the authentication server, you can use the ssoSilent() API
+ * to make request for tokens without interaction, by providing a "login_hint" property. To try this, comment the
+ * line above and uncomment the section below.
+ */
+
+ // myMSALObj.ssoSilent(silentRequest).
+ // then(() => {
+ // const currentAccounts = myMSALObj.getAllAccounts();
+ // username = currentAccounts[0].username;
+ // welcomeUser(username);
+ // updateTable();
+ // }).catch(error => {
+ // console.error("Silent Error: " + error);
+ // if (error instanceof msal.InteractionRequiredAuthError) {
+ // signIn();
+ // }
+ // });
+ }
+}
+
+function signIn() {
+
+ /**
+ * You can pass a custom request object below. This will override the initial configuration. For more information, visit:
+ * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/request-response-object.md#request
+ */
+
+ myMSALObj.loginRedirect(loginRequest);
+}
+
+function signOut() {
+
+ /**
+ * You can pass a custom request object below. This will override the initial configuration. For more information, visit:
+ * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/request-response-object.md#request
+ */
+
+ // Choose which account to logout from by passing a username.
+ const logoutRequest = {
+ account: myMSALObj.getAccountByUsername(username),
+ postLogoutRedirectUri: 'http://localhost:3000/signout', // Simply remove this line if you would like navigate to index page after logout.
+
+ };
+
+ myMSALObj.logoutRedirect(logoutRequest);
+}
diff --git a/App/favicon.svg b/App/favicon.svg
new file mode 100644
index 0000000..1284553
--- /dev/null
+++ b/App/favicon.svg
@@ -0,0 +1,23 @@
+
diff --git a/App/index.html b/App/index.html
new file mode 100644
index 0000000..13c9318
--- /dev/null
+++ b/App/index.html
@@ -0,0 +1,74 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/App/ui.js b/App/ui.js
new file mode 100644
index 0000000..72f7290
--- /dev/null
+++ b/App/ui.js
@@ -0,0 +1,55 @@
+// Select DOM elements to work with
+const signInButton = document.getElementById('signIn');
+const signOutButton = document.getElementById('signOut')
+const titleDiv = document.getElementById('title-div');
+const welcomeDiv = document.getElementById('welcome-div');
+const tableDiv = document.getElementById('table-div');
+const footerDiv = document.getElementById('footer');
+const tableBody = document.getElementById('table-body-div');
+
+function welcomeUser(username) {
+ signInButton.classList.add('d-none');
+ signOutButton.classList.remove('d-none');
+ titleDiv.classList.add('d-none');
+ welcomeDiv.classList.remove('d-none');
+ welcomeDiv.innerHTML = `Welcome ${username}!`
+}
+
+function updateTable() {
+
+ /**
+ * In order to obtain the ID Token in the cached obtained previously, you can initiate a
+ * silent token request by passing the current user's account and the scope "openid".
+ */
+ myMSALObj.acquireTokenSilent({
+ account: myMSALObj.getAccountByUsername(username),
+ scopes: ["openid"]
+ }).then(response => {
+
+ tableDiv.classList.remove('d-none');
+ footerDiv.classList.remove('d-none');
+
+ console.log("printing the token now:");
+ console.log(response);
+ console.log(response.idTokenClaims);
+
+ Object.entries(response.idTokenClaims).forEach(claim => {
+
+ if (claim[0] === "name" || claim[0] === "preferred_username" || claim[0] === "groups" || claim[0] === "roles") {
+ let row = tableBody.insertRow(0);
+ let cell1 = row.insertCell(0);
+ let cell2 = row.insertCell(1);
+ cell1.innerHTML = claim[0];
+ cell2.innerHTML = claim[1];
+ }
+
+ // let row = tableBody.insertRow(0);
+ // let cell1 = row.insertCell(0);
+ // let cell2 = row.insertCell(1);
+ // cell1.innerHTML = claim[0];
+ // cell2.innerHTML = claim[1];
+
+
+ });
+ });
+}
\ No newline at end of file
diff --git a/AppCreationScripts/AppCreationScripts.md b/AppCreationScripts/AppCreationScripts.md
new file mode 100644
index 0000000..6e062df
--- /dev/null
+++ b/AppCreationScripts/AppCreationScripts.md
@@ -0,0 +1,148 @@
+# 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. 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.
+
+ ```PowerShell
+ cd .\AppCreationScripts\
+ .\Configure.ps1 -TenantId "your test tenant's id" -AzureEnvironmentName "[Optional] - Azure environment, defaults to 'Global'"
+ ```
+
+### 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 (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
+
+### 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, 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`).
+
+### 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)
+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 Microsoft.Graph.Applications PowerShell modules
+
+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 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**).
+ 2. Type:
+
+ ```PowerShell
+ Install-Module Microsoft.Graph.Applications
+ ```
+
+ or if you cannot be administrator on your machine, run:
+
+ ```PowerShell
+ Install-Module Microsoft.Graph.Applications -Scope CurrentUser
+ ```
+
+### Run the script and start running
+
+1. Go to the `AppCreationScripts` sub-folder. From the folder where you cloned the repo,
+
+ ```PowerShell
+ cd AppCreationScripts
+ ```
+
+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!
+
+### 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,
+- 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).
+- 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 (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
+```
+
+### 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`.
+
+The acceptable values for this parameter are:
+
+- AzureCloud
+- AzureChinaCloud
+- AzureUSGovernment
+
+Example:
+
+ ```PowerShell
+ . .\Cleanup.ps1 -AzureEnvironmentName "AzureUSGovernment"
+ . .\Configure.ps1 -AzureEnvironmentName "AzureUSGovernment"
+ ```
diff --git a/AppCreationScripts/Cleanup.ps1 b/AppCreationScripts/Cleanup.ps1
new file mode 100644
index 0000000..72aaef8
--- /dev/null
+++ b/AppCreationScripts/Cleanup.ps1
@@ -0,0 +1,151 @@
+
+[CmdletBinding()]
+param(
+ [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. Default = Global')]
+ [string] $azureEnvironmentName
+)
+
+
+Function Cleanup
+{
+ if (!$azureEnvironmentName)
+ {
+ $azureEnvironmentName = "Global"
+ }
+
+ <#
+ .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.
+
+ # Connect to the Microsoft Graph API
+ Write-Host "Connecting to Microsoft Graph"
+
+
+ if ($tenantId -eq "")
+ {
+ Connect-MgGraph -Scopes "User.Read.All Organization.Read.All Application.ReadWrite.All" -Environment $azureEnvironmentName
+ }
+ else
+ {
+ Connect-MgGraph -TenantId $tenantId -Scopes "User.Read.All Organization.Read.All Application.ReadWrite.All" -Environment $azureEnvironmentName
+ }
+
+ $context = Get-MgContext
+ $tenantId = $context.TenantId
+
+ # Get the user running the script
+ $currentUserPrincipalName = $context.Account
+ $user = Get-MgUser -Filter "UserPrincipalName eq '$($context.Account)'"
+
+ # get the tenant we signed in to
+ $Tenant = Get-MgOrganization
+ $tenantName = $Tenant.DisplayName
+
+ $verifiedDomain = $Tenant.VerifiedDomains | where {$_.Isdefault -eq $true}
+ $verifiedDomainName = $verifiedDomain.Name
+ $tenantId = $Tenant.Id
+
+ Write-Host ("Connected to Tenant {0} ({1}) as account '{2}'. Domain is '{3}'" -f $Tenant.DisplayName, $Tenant.Id, $currentUserPrincipalName, $verifiedDomainName)
+
+ # Removes the applications
+ Write-Host "Cleaning-up applications from tenant '$tenantId'"
+
+ Write-Host "Removing 'client' (ms-identity-javascript-c1s1) if needed"
+ try
+ {
+ Get-MgApplication -Filter "DisplayName eq 'ms-identity-javascript-c1s1'" | ForEach-Object {Remove-MgApplication -ApplicationId $_.Id }
+ }
+ catch
+ {
+ $message = $_
+ Write-Warning $Error[0]
+ Write-Host "Unable to remove the application 'ms-identity-javascript-c1s1'. Error is $message. Try deleting manually." -ForegroundColor White -BackgroundColor Red
+ }
+
+ Write-Host "Making sure there are no more (ms-identity-javascript-c1s1) applications found, will remove if needed..."
+ $apps = Get-MgApplication -Filter "DisplayName eq 'ms-identity-javascript-c1s1'" | Format-List Id, DisplayName, AppId, SignInAudience, PublisherDomain
+
+ if ($apps)
+ {
+ Remove-MgApplication -ApplicationId $apps.Id
+ }
+
+ foreach ($app in $apps)
+ {
+ Remove-MgApplication -ApplicationId $app.Id
+ Write-Host "Removed ms-identity-javascript-c1s1.."
+ }
+
+ # also remove service principals of this app
+ try
+ {
+ Get-MgServicePrincipal -filter "DisplayName eq 'ms-identity-javascript-c1s1'" | ForEach-Object {Remove-MgServicePrincipal -ServicePrincipalId $_.Id -Confirm:$false}
+ }
+ catch
+ {
+ $message = $_
+ Write-Warning $Error[0]
+ Write-Host "Unable to remove ServicePrincipal 'ms-identity-javascript-c1s1'. Error is $message. Try deleting manually from Enterprise applications." -ForegroundColor White -BackgroundColor Red
+ }
+}
+
+# Pre-requisites
+if ($null -eq (Get-Module -ListAvailable -Name "Microsoft.Graph")) {
+ Install-Module "Microsoft.Graph" -Scope CurrentUser
+}
+
+#Import-Module Microsoft.Graph
+
+if ($null -eq (Get-Module -ListAvailable -Name "Microsoft.Graph.Authentication")) {
+ Install-Module "Microsoft.Graph.Authentication" -Scope CurrentUser
+}
+
+Import-Module Microsoft.Graph.Authentication
+
+if ($null -eq (Get-Module -ListAvailable -Name "Microsoft.Graph.Identity.DirectoryManagement")) {
+ Install-Module "Microsoft.Graph.Identity.DirectoryManagement" -Scope CurrentUser
+}
+
+Import-Module Microsoft.Graph.Identity.DirectoryManagement
+
+if ($null -eq (Get-Module -ListAvailable -Name "Microsoft.Graph.Applications")) {
+ Install-Module "Microsoft.Graph.Applications" -Scope CurrentUser
+}
+
+Import-Module Microsoft.Graph.Applications
+
+if ($null -eq (Get-Module -ListAvailable -Name "Microsoft.Graph.Groups")) {
+ Install-Module "Microsoft.Graph.Groups" -Scope CurrentUser
+}
+
+Import-Module Microsoft.Graph.Groups
+
+if ($null -eq (Get-Module -ListAvailable -Name "Microsoft.Graph.Users")) {
+ Install-Module "Microsoft.Graph.Users" -Scope CurrentUser
+}
+
+Import-Module Microsoft.Graph.Users
+
+$ErrorActionPreference = "Stop"
+
+
+try
+{
+ Cleanup -tenantId $tenantId -environment $azureEnvironmentName
+}
+catch
+{
+ $_.Exception.ToString() | out-host
+ $message = $_
+ Write-Warning $Error[0]
+ Write-Host "Unable to register apps. Error is $message." -ForegroundColor White -BackgroundColor Red
+}
+
+Write-Host "Disconnecting from tenant"
+Disconnect-MgGraph
diff --git a/AppCreationScripts/Configure.ps1 b/AppCreationScripts/Configure.ps1
new file mode 100644
index 0000000..a2043d4
--- /dev/null
+++ b/AppCreationScripts/Configure.ps1
@@ -0,0 +1,288 @@
+
+[CmdletBinding()]
+param(
+ [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. Default = Global')]
+ [string] $azureEnvironmentName
+)
+
+<#
+ 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.
+
+ In case you don't have Microsoft.Graph.Applications already installed, the script will automatically install it for the current user
+
+ There are two ways to run this script. For more information, read the AppCreationScripts.md file in the same folder as this script.
+#>
+
+<#.Description
+ This function takes a string input as a single line, matches a key value and replaces with the replacement value
+#>
+Function UpdateLine([string] $line, [string] $value)
+{
+ $index = $line.IndexOf(':')
+ $lineEnd = ''
+
+ if($line[$line.Length - 1] -eq ','){ $lineEnd = ',' }
+
+ if ($index -ige 0)
+ {
+ $line = $line.Substring(0, $index+1) + " " + '"' + $value+ '"' + $lineEnd
+ }
+ return $line
+}
+
+<#.Description
+ This function takes a dictionary of keys to search and their replacements and replaces the placeholders in a text file
+#>
+Function UpdateTextFile([string] $configFilePath, [System.Collections.HashTable] $dictionary)
+{
+ $lines = Get-Content $configFilePath
+ $index = 0
+ while($index -lt $lines.Length)
+ {
+ $line = $lines[$index]
+ foreach($key in $dictionary.Keys)
+ {
+ if ($line.Contains($key))
+ {
+ $lines[$index] = UpdateLine $line $dictionary[$key]
+ }
+ }
+ $index++
+ }
+
+ Set-Content -Path $configFilePath -Value $lines -Force
+}
+
+<#.Description
+ This function takes a string input as a single line, matches a key value and replaces with the replacement value
+#>
+Function ReplaceInLine([string] $line, [string] $key, [string] $value)
+{
+ $index = $line.IndexOf($key)
+ if ($index -ige 0)
+ {
+ $index2 = $index+$key.Length
+ $line = $line.Substring(0, $index) + $value + $line.Substring($index2)
+ }
+ return $line
+}
+
+<#.Description
+ This function takes a dictionary of keys to search and their replacements and replaces the placeholders in a text file
+#>
+Function ReplaceInTextFile([string] $configFilePath, [System.Collections.HashTable] $dictionary)
+{
+ $lines = Get-Content $configFilePath
+ $index = 0
+ while($index -lt $lines.Length)
+ {
+ $line = $lines[$index]
+ foreach($key in $dictionary.Keys)
+ {
+ if ($line.Contains($key))
+ {
+ $lines[$index] = ReplaceInLine $line $key $dictionary[$key]
+ }
+ }
+ $index++
+ }
+
+ Set-Content -Path $configFilePath -Value $lines -Force
+}
+
+
+<#.Description
+ This function takes a string as input and creates an instance of an Optional claim object
+#>
+Function CreateOptionalClaim([string] $name)
+{
+ <#.Description
+ This function creates a new Azure AD optional claims with default and provided values
+ #>
+
+ $appClaim = New-Object Microsoft.Graph.PowerShell.Models.MicrosoftGraphOptionalClaim
+ $appClaim.AdditionalProperties = New-Object System.Collections.Generic.List[string]
+ $appClaim.Source = $null
+ $appClaim.Essential = $false
+ $appClaim.Name = $name
+ return $appClaim
+}
+
+<#.Description
+ Primary entry method to create and configure app registrations
+#>
+Function ConfigureApplications
+{
+ $isOpenSSl = 'N' #temporary disable open certificate creation
+
+ <#.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
+ #>
+
+ if (!$azureEnvironmentName)
+ {
+ $azureEnvironmentName = "Global"
+ }
+
+ # Connect to the Microsoft Graph API, non-interactive is not supported for the moment (Oct 2021)
+ Write-Host "Connecting to Microsoft Graph"
+ if ($tenantId -eq "") {
+ Connect-MgGraph -Scopes "User.Read.All Organization.Read.All Application.ReadWrite.All" -Environment $azureEnvironmentName
+ }
+ else {
+ Connect-MgGraph -TenantId $tenantId -Scopes "User.Read.All Organization.Read.All Application.ReadWrite.All" -Environment $azureEnvironmentName
+ }
+
+ $context = Get-MgContext
+ $tenantId = $context.TenantId
+
+ # Get the user running the script
+ $currentUserPrincipalName = $context.Account
+ $user = Get-MgUser -Filter "UserPrincipalName eq '$($context.Account)'"
+
+ # get the tenant we signed in to
+ $Tenant = Get-MgOrganization
+ $tenantName = $Tenant.DisplayName
+
+ $verifiedDomain = $Tenant.VerifiedDomains | where {$_.Isdefault -eq $true}
+ $verifiedDomainName = $verifiedDomain.Name
+ $tenantId = $Tenant.Id
+
+ Write-Host ("Connected to Tenant {0} ({1}) as account '{2}'. Domain is '{3}'" -f $Tenant.DisplayName, $Tenant.Id, $currentUserPrincipalName, $verifiedDomainName)
+
+ # Create the client AAD application
+ Write-Host "Creating the AAD application (ms-identity-javascript-c1s1)"
+ # create the application
+ $clientAadApplication = New-MgApplication -DisplayName "ms-identity-javascript-c1s1" `
+ -Spa `
+ @{ `
+ RedirectUris = "http://localhost:3000", "http://localhost:3000/redirect"; `
+ } `
+ -SignInAudience AzureADMyOrg `
+ #end of command
+
+ $currentAppId = $clientAadApplication.AppId
+ $currentAppObjectId = $clientAadApplication.Id
+
+ $tenantName = (Get-MgApplication -ApplicationId $currentAppObjectId).PublisherDomain
+ #Update-MgApplication -ApplicationId $currentAppObjectId -IdentifierUris @("https://$tenantName/ms-identity-javascript-c1s1")
+
+ # create the service principal of the newly created application
+ $clientServicePrincipal = New-MgServicePrincipal -AppId $currentAppId -Tags {WindowsAzureActiveDirectoryIntegratedApp}
+
+ # add the user running the script as an app owner if needed
+ $owner = Get-MgApplicationOwner -ApplicationId $currentAppObjectId
+ if ($owner -eq $null)
+ {
+ New-MgApplicationOwnerByRef -ApplicationId $currentAppObjectId -BodyParameter = @{"@odata.id" = "htps://graph.microsoft.com/v1.0/directoryObjects/$user.ObjectId"}
+ Write-Host "'$($user.UserPrincipalName)' added as an application owner to app '$($clientServicePrincipal.DisplayName)'"
+ }
+
+ # Add Claims
+
+ $optionalClaims = New-Object Microsoft.Graph.PowerShell.Models.MicrosoftGraphOptionalClaims
+ $optionalClaims.AccessToken = New-Object System.Collections.Generic.List[Microsoft.Graph.PowerShell.Models.MicrosoftGraphOptionalClaim]
+ $optionalClaims.IdToken = New-Object System.Collections.Generic.List[Microsoft.Graph.PowerShell.Models.MicrosoftGraphOptionalClaim]
+ $optionalClaims.Saml2Token = New-Object System.Collections.Generic.List[Microsoft.Graph.PowerShell.Models.MicrosoftGraphOptionalClaim]
+
+ # Add Optional Claims
+
+ $newClaim = CreateOptionalClaim -name "acct"
+ $optionalClaims.IdToken += ($newClaim)
+ Update-MgApplication -ApplicationId $currentAppObjectId -OptionalClaims $optionalClaims
+ Write-Host "Done creating the client application (ms-identity-javascript-c1s1)"
+
+ # URL of the AAD application in the Azure portal
+ # Future? $clientPortalUrl = "https://portal.azure.com/#@"+$tenantName+"/blade/Microsoft_AAD_RegisteredApps/ApplicationMenuBlade/Overview/appId/"+$currentAppId+"/objectId/"+$currentAppObjectId+"/isMSAApp/"
+ $clientPortalUrl = "https://portal.azure.com/#blade/Microsoft_AAD_RegisteredApps/ApplicationMenuBlade/CallAnAPI/appId/"+$currentAppId+"/objectId/"+$currentAppObjectId+"/isMSAApp/"
+
+ Add-Content -Value "