├── .github ├── CODE_OF_CONDUCT.md ├── ISSUE_TEMPLATE.md └── PULL_REQUEST_TEMPLATE.md ├── .gitignore ├── AppCreationScripts ├── AppCreationScripts.md ├── Cleanup.ps1 ├── Configure.ps1 └── sample.json ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE.md ├── README.md ├── ReadmeFiles ├── ReadmeAboutTheCode.md ├── ReadmeExploreTheSample.md ├── ReadmeHowTheCodeWasCreated.md ├── ReadmeLearnMore.md ├── ReadmeNextSteps.md ├── ReadmePrerequirements.md ├── ReadmeTroubleshooting.md ├── topology.png └── topology.vsdx ├── WinUIMSALApp ├── App.xaml ├── App.xaml.cs ├── Assets │ ├── LockScreenLogo.scale-200.png │ ├── SplashScreen.scale-200.png │ ├── Square150x150Logo.scale-200.png │ ├── Square44x44Logo.scale-200.png │ ├── Square44x44Logo.targetsize-24_altform-unplated.png │ ├── StoreLogo.png │ └── Wide310x150Logo.scale-200.png ├── MSAL │ ├── AzureADConfig.cs │ ├── IdentityLogger.cs │ ├── MSALClientHelper.cs │ ├── MSGraphApiConfig.cs │ └── MSGraphHelper.cs ├── MainWindow.xaml ├── MainWindow.xaml.cs ├── Package.appxmanifest ├── Properties │ └── launchSettings.json ├── WinUIMSALApp.csproj ├── app.manifest └── appsettings.json └── ms-identity-netcore-winui.sln /.github/CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Microsoft Open Source Code of Conduct 2 | 3 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). 4 | 5 | Resources: 6 | 7 | - [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/) 8 | - [Microsoft Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) 9 | - Contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with questions or concerns 10 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 4 | > Please provide us with the following information: 5 | > --------------------------------------------------------------- 6 | 7 | ### This issue is for a: (mark with an `x`) 8 | ``` 9 | - [ ] bug report -> please search issues before submitting 10 | - [ ] feature request 11 | - [ ] documentation issue or request 12 | - [ ] regression (a behavior that used to work and stopped in a new release) 13 | ``` 14 | 15 | ### Minimal steps to reproduce 16 | > 17 | 18 | ### Any log messages given by the failure 19 | > 20 | 21 | ### Expected/desired behavior 22 | > 23 | 24 | ### OS and Version? 25 | > Windows 7, 8 or 10. Linux (which distribution). macOS (Yosemite? El Capitan? Sierra?) 26 | 27 | ### Versions 28 | > 29 | 30 | ### Mention any other details that might be useful 31 | 32 | > --------------------------------------------------------------- 33 | > Thanks! We'll be in touch soon. 34 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ## Purpose 2 | 3 | * ... 4 | 5 | ## Does this introduce a breaking change? 6 | 7 | ``` 8 | [ ] Yes 9 | [ ] No 10 | ``` 11 | 12 | ## Pull Request Type 13 | What kind of change does this Pull Request introduce? 14 | 15 | 16 | ``` 17 | [ ] Bugfix 18 | [ ] Feature 19 | [ ] Code style update (formatting, local variables) 20 | [ ] Refactoring (no functional changes, no api changes) 21 | [ ] Documentation content changes 22 | [ ] Other... Please describe: 23 | ``` 24 | 25 | ## How to Test 26 | * Get the code 27 | 28 | ``` 29 | git clone [repo-address] 30 | cd [repo-name] 31 | git checkout [branch-name] 32 | npm install 33 | ``` 34 | 35 | * Test the code 36 | 37 | ``` 38 | ``` 39 | 40 | ## What to Check 41 | Verify that the following are valid 42 | * ... 43 | 44 | ## Other Information 45 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | [Ll]ogs/ 33 | 34 | # Visual Studio 2015/2017 cache/options directory 35 | .vs/ 36 | # Uncomment if you have tasks that create the project's static files in wwwroot 37 | #wwwroot/ 38 | 39 | # Visual Studio 2017 auto generated files 40 | Generated\ Files/ 41 | 42 | # MSTest test Results 43 | [Tt]est[Rr]esult*/ 44 | [Bb]uild[Ll]og.* 45 | 46 | # NUnit 47 | *.VisualState.xml 48 | TestResult.xml 49 | nunit-*.xml 50 | 51 | # Build Results of an ATL Project 52 | [Dd]ebugPS/ 53 | [Rr]eleasePS/ 54 | dlldata.c 55 | 56 | # Benchmark Results 57 | BenchmarkDotNet.Artifacts/ 58 | 59 | # .NET Core 60 | project.lock.json 61 | project.fragment.lock.json 62 | artifacts/ 63 | 64 | # StyleCop 65 | StyleCopReport.xml 66 | 67 | # Files built by Visual Studio 68 | *_i.c 69 | *_p.c 70 | *_h.h 71 | *.ilk 72 | *.meta 73 | *.obj 74 | *.iobj 75 | *.pch 76 | *.pdb 77 | *.ipdb 78 | *.pgc 79 | *.pgd 80 | *.rsp 81 | *.sbr 82 | *.tlb 83 | *.tli 84 | *.tlh 85 | *.tmp 86 | *.tmp_proj 87 | *_wpftmp.csproj 88 | *.log 89 | *.vspscc 90 | *.vssscc 91 | .builds 92 | *.pidb 93 | *.svclog 94 | *.scc 95 | 96 | # Chutzpah Test files 97 | _Chutzpah* 98 | 99 | # Visual C++ cache files 100 | ipch/ 101 | *.aps 102 | *.ncb 103 | *.opendb 104 | *.opensdf 105 | *.sdf 106 | *.cachefile 107 | *.VC.db 108 | *.VC.VC.opendb 109 | 110 | # Visual Studio profiler 111 | *.psess 112 | *.vsp 113 | *.vspx 114 | *.sap 115 | 116 | # Visual Studio Trace Files 117 | *.e2e 118 | 119 | # TFS 2012 Local Workspace 120 | $tf/ 121 | 122 | # Guidance Automation Toolkit 123 | *.gpState 124 | 125 | # ReSharper is a .NET coding add-in 126 | _ReSharper*/ 127 | *.[Rr]e[Ss]harper 128 | *.DotSettings.user 129 | 130 | # TeamCity is a build add-in 131 | _TeamCity* 132 | 133 | # DotCover is a Code Coverage Tool 134 | *.dotCover 135 | 136 | # AxoCover is a Code Coverage Tool 137 | .axoCover/* 138 | !.axoCover/settings.json 139 | 140 | # Visual Studio code coverage results 141 | *.coverage 142 | *.coveragexml 143 | 144 | # NCrunch 145 | _NCrunch_* 146 | .*crunch*.local.xml 147 | nCrunchTemp_* 148 | 149 | # MightyMoose 150 | *.mm.* 151 | AutoTest.Net/ 152 | 153 | # Web workbench (sass) 154 | .sass-cache/ 155 | 156 | # Installshield output folder 157 | [Ee]xpress/ 158 | 159 | # DocProject is a documentation generator add-in 160 | DocProject/buildhelp/ 161 | DocProject/Help/*.HxT 162 | DocProject/Help/*.HxC 163 | DocProject/Help/*.hhc 164 | DocProject/Help/*.hhk 165 | DocProject/Help/*.hhp 166 | DocProject/Help/Html2 167 | DocProject/Help/html 168 | 169 | # Click-Once directory 170 | publish/ 171 | 172 | # Publish Web Output 173 | *.[Pp]ublish.xml 174 | *.azurePubxml 175 | # Note: Comment the next line if you want to checkin your web deploy settings, 176 | # but database connection strings (with potential passwords) will be unencrypted 177 | *.pubxml 178 | *.publishproj 179 | 180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 181 | # checkin your Azure Web App publish settings, but sensitive information contained 182 | # in these scripts will be unencrypted 183 | PublishScripts/ 184 | 185 | # NuGet Packages 186 | *.nupkg 187 | # NuGet Symbol Packages 188 | *.snupkg 189 | # The packages folder can be ignored because of Package Restore 190 | **/[Pp]ackages/* 191 | # except build/, which is used as an MSBuild target. 192 | !**/[Pp]ackages/build/ 193 | # Uncomment if necessary however generally it will be regenerated when needed 194 | #!**/[Pp]ackages/repositories.config 195 | # NuGet v3's project.json files produces more ignorable files 196 | *.nuget.props 197 | *.nuget.targets 198 | 199 | # Microsoft Azure Build Output 200 | csx/ 201 | *.build.csdef 202 | 203 | # Microsoft Azure Emulator 204 | ecf/ 205 | rcf/ 206 | 207 | # Windows Store app package directories and files 208 | AppPackages/ 209 | BundleArtifacts/ 210 | Package.StoreAssociation.xml 211 | _pkginfo.txt 212 | *.appx 213 | *.appxbundle 214 | *.appxupload 215 | 216 | # Visual Studio cache files 217 | # files ending in .cache can be ignored 218 | *.[Cc]ache 219 | # but keep track of directories ending in .cache 220 | !?*.[Cc]ache/ 221 | 222 | # Others 223 | ClientBin/ 224 | ~$* 225 | *~ 226 | *.dbmdl 227 | *.dbproj.schemaview 228 | *.jfm 229 | *.pfx 230 | *.publishsettings 231 | orleans.codegen.cs 232 | 233 | # Including strong name files can present a security risk 234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 235 | #*.snk 236 | 237 | # Since there are multiple workflows, uncomment next line to ignore bower_components 238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 239 | #bower_components/ 240 | 241 | # RIA/Silverlight projects 242 | Generated_Code/ 243 | 244 | # Backup & report files from converting an old project file 245 | # to a newer Visual Studio version. Backup files are not needed, 246 | # because we have git ;-) 247 | _UpgradeReport_Files/ 248 | Backup*/ 249 | UpgradeLog*.XML 250 | UpgradeLog*.htm 251 | ServiceFabricBackup/ 252 | *.rptproj.bak 253 | 254 | # SQL Server files 255 | *.mdf 256 | *.ldf 257 | *.ndf 258 | 259 | # Business Intelligence projects 260 | *.rdl.data 261 | *.bim.layout 262 | *.bim_*.settings 263 | *.rptproj.rsuser 264 | *- [Bb]ackup.rdl 265 | *- [Bb]ackup ([0-9]).rdl 266 | *- [Bb]ackup ([0-9][0-9]).rdl 267 | 268 | # Microsoft Fakes 269 | FakesAssemblies/ 270 | 271 | # GhostDoc plugin setting file 272 | *.GhostDoc.xml 273 | 274 | # Node.js Tools for Visual Studio 275 | .ntvs_analysis.dat 276 | node_modules/ 277 | 278 | # Visual Studio 6 build log 279 | *.plg 280 | 281 | # Visual Studio 6 workspace options file 282 | *.opt 283 | 284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 285 | *.vbw 286 | 287 | # Visual Studio LightSwitch build output 288 | **/*.HTMLClient/GeneratedArtifacts 289 | **/*.DesktopClient/GeneratedArtifacts 290 | **/*.DesktopClient/ModelManifest.xml 291 | **/*.Server/GeneratedArtifacts 292 | **/*.Server/ModelManifest.xml 293 | _Pvt_Extensions 294 | 295 | # Paket dependency manager 296 | .paket/paket.exe 297 | paket-files/ 298 | 299 | # FAKE - F# Make 300 | .fake/ 301 | 302 | # CodeRush personal settings 303 | .cr/personal 304 | 305 | # Python Tools for Visual Studio (PTVS) 306 | __pycache__/ 307 | *.pyc 308 | 309 | # Cake - Uncomment if you are using it 310 | # tools/** 311 | # !tools/packages.config 312 | 313 | # Tabs Studio 314 | *.tss 315 | 316 | # Telerik's JustMock configuration file 317 | *.jmconfig 318 | 319 | # BizTalk build output 320 | *.btp.cs 321 | *.btm.cs 322 | *.odx.cs 323 | *.xsd.cs 324 | 325 | # OpenCover UI analysis results 326 | OpenCover/ 327 | 328 | # Azure Stream Analytics local run output 329 | ASALocalRun/ 330 | 331 | # MSBuild Binary and Structured Log 332 | *.binlog 333 | 334 | # NVidia Nsight GPU debugger configuration file 335 | *.nvuser 336 | 337 | # MFractors (Xamarin productivity tool) working folder 338 | .mfractor/ 339 | 340 | # Local History for Visual Studio 341 | .localhistory/ 342 | 343 | # BeatPulse healthcheck temp database 344 | healthchecksdb 345 | 346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 347 | MigrationBackup/ 348 | 349 | # Ionide (cross platform F# VS Code tools) working folder 350 | .ionide/ 351 | -------------------------------------------------------------------------------- /AppCreationScripts/AppCreationScripts.md: -------------------------------------------------------------------------------- 1 | # Registering sample apps with the Microsoft identity platform and updating configuration files using PowerShell 2 | 3 | ## Overview 4 | 5 | ### Quick summary 6 | 7 | 1. On Windows, run PowerShell as **Administrator** and navigate to the root of the cloned directory 8 | 1. In PowerShell run: 9 | 10 | ```PowerShell 11 | Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process -Force 12 | ``` 13 | 14 | 1. Run the script to create your Azure AD application and configure the code of the sample application accordingly. 15 | 16 | ```PowerShell 17 | cd .\AppCreationScripts\ 18 | .\Configure.ps1 -TenantId "your test tenant's id" -AzureEnvironmentName "[Optional] - Azure environment, defaults to 'Global'" 19 | ``` 20 | 21 | ### More details 22 | 23 | - [Goal of the provided scripts](#goal-of-the-provided-scripts) 24 | - [Presentation of the scripts](#presentation-of-the-scripts) 25 | - [Usage pattern for tests and DevOps scenarios](#usage-pattern-for-tests-and-DevOps-scenarios) 26 | - [How to use the app creation scripts?](#how-to-use-the-app-creation-scripts) 27 | - [Pre-requisites](#pre-requisites) 28 | - [Run the script and start running](#run-the-script-and-start-running) 29 | - [Four ways to run the script](#four-ways-to-run-the-script) 30 | - [Option 1 (interactive)](#option-1-interactive) 31 | - [Option 2 (Interactive, but create apps in a specified tenant)](#option-3-Interactive-but-create-apps-in-a-specified-tenant) 32 | - [Running the script on Azure Sovereign clouds](#running-the-script-on-Azure-Sovereign-clouds) 33 | 34 | ## Goal of the provided scripts 35 | 36 | ### Presentation of the scripts 37 | 38 | 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. 39 | 40 | These scripts are: 41 | 42 | - `Configure.ps1` which: 43 | - creates Azure AD applications and their related objects (permissions, dependencies, secrets, app roles), 44 | - changes the configuration files in the sample projects. 45 | - 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: 46 | - the identifier of the application 47 | - the AppId of the application 48 | - the url of its registration in the [Azure portal](https://portal.azure.com). 49 | 50 | - `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`). 51 | 52 | ### Usage pattern for tests and DevOps scenarios 53 | 54 | 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. 55 | 56 | ## How to use the app creation scripts? 57 | 58 | ### Pre-requisites 59 | 60 | 1. Open PowerShell (On Windows, press `Windows-R` and type `PowerShell` in the search window) 61 | 1. Navigate to the root directory of the project. 62 | 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: 63 | 64 | ```PowerShell 65 | Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process 66 | ``` 67 | 68 | ### (Optionally) install Microsoft.Graph.Applications PowerShell modules 69 | 70 | 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: 71 | 72 | 1. If you have never done it already, in the PowerShell window, install the Microsoft.Graph.Applications PowerShell modules. For this: 73 | 74 | 1. Open PowerShell as admin (On Windows, Search Powershell in the search bar, right click on it and select **Run as administrator**). 75 | 2. Type: 76 | 77 | ```PowerShell 78 | Install-Module Microsoft.Graph.Applications 79 | ``` 80 | 81 | or if you cannot be administrator on your machine, run: 82 | 83 | ```PowerShell 84 | Install-Module Microsoft.Graph.Applications -Scope CurrentUser 85 | ``` 86 | 87 | ### Run the script and start running 88 | 89 | 1. Go to the `AppCreationScripts` sub-folder. From the folder where you cloned the repo, 90 | 91 | ```PowerShell 92 | cd AppCreationScripts 93 | ``` 94 | 95 | 1. Run the scripts. See below for the [four options](#four-ways-to-run-the-script) to do that. 96 | 1. Open the Visual Studio solution, and in the solution's context menu, choose **Set Startup Projects**. 97 | 1. select **Start** for the projects 98 | 99 | You're done! 100 | 101 | ### Two ways to run the script 102 | 103 | We advise four ways of running the script: 104 | 105 | - Interactive: you will be prompted for credentials, and the scripts decide in which tenant to create the objects, 106 | - 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, 107 | 108 | Here are the details on how to do this. 109 | 110 | #### Option 1 (interactive) 111 | 112 | - Just run ``.\Configure.ps1``, and you will be prompted to sign-in (email address, password, and if needed MFA). 113 | - The script will be run as the signed-in user and will use the tenant in which the user is defined. 114 | 115 | 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. 116 | 117 | #### Option 2 (Interactive, but create apps in a specified tenant) 118 | 119 | if you want to create the apps in a particular tenant, you can use the following option: 120 | 121 | - Open the [Azure portal](https://portal.azure.com) 122 | - Select the Azure Active directory you are interested in (in the combo-box below your name on the top right of the browser window) 123 | - Find the "Active Directory" object in this tenant 124 | - Go to **Properties** and copy the content of the **Directory Id** property 125 | - Then use the full syntax to run the scripts: 126 | 127 | ```PowerShell 128 | $tenantId = "yourTenantIdGuid" 129 | . .\Cleanup.ps1 -TenantId $tenantId 130 | . .\Configure.ps1 -TenantId $tenantId 131 | ``` 132 | 133 | ### Running the script on Azure Sovereign clouds 134 | 135 | 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`. 136 | 137 | The acceptable values for this parameter are: 138 | 139 | - AzureCloud 140 | - AzureChinaCloud 141 | - AzureUSGovernment 142 | 143 | Example: 144 | 145 | ```PowerShell 146 | . .\Cleanup.ps1 -AzureEnvironmentName "AzureUSGovernment" 147 | . .\Configure.ps1 -AzureEnvironmentName "AzureUSGovernment" 148 | ``` 149 | -------------------------------------------------------------------------------- /AppCreationScripts/Cleanup.ps1: -------------------------------------------------------------------------------- 1 | 2 | [CmdletBinding()] 3 | param( 4 | [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')] 5 | [string] $tenantId, 6 | [Parameter(Mandatory=$False, HelpMessage='Azure environment to use while running the script. Default = Global')] 7 | [string] $azureEnvironmentName 8 | ) 9 | 10 | 11 | Function Cleanup 12 | { 13 | if (!$azureEnvironmentName) 14 | { 15 | $azureEnvironmentName = "Global" 16 | } 17 | 18 | <# 19 | .Description 20 | This function removes the Azure AD applications for the sample. These applications were created by the Configure.ps1 script 21 | #> 22 | 23 | # $tenantId is the Active Directory Tenant. This is a GUID which represents the "Directory ID" of the AzureAD tenant 24 | # into which you want to create the apps. Look it up in the Azure portal in the "Properties" of the Azure AD. 25 | 26 | # Connect to the Microsoft Graph API 27 | Write-Host "Connecting to Microsoft Graph" 28 | 29 | 30 | if ($tenantId -eq "") 31 | { 32 | Connect-MgGraph -Scopes "User.Read.All Organization.Read.All Application.ReadWrite.All" -Environment $azureEnvironmentName 33 | } 34 | else 35 | { 36 | Connect-MgGraph -TenantId $tenantId -Scopes "User.Read.All Organization.Read.All Application.ReadWrite.All" -Environment $azureEnvironmentName 37 | } 38 | 39 | $context = Get-MgContext 40 | $tenantId = $context.TenantId 41 | 42 | # Get the user running the script 43 | $currentUserPrincipalName = $context.Account 44 | $user = Get-MgUser -Filter "UserPrincipalName eq '$($context.Account)'" 45 | 46 | # get the tenant we signed in to 47 | $Tenant = Get-MgOrganization 48 | $tenantName = $Tenant.DisplayName 49 | 50 | $verifiedDomain = $Tenant.VerifiedDomains | where {$_.Isdefault -eq $true} 51 | $verifiedDomainName = $verifiedDomain.Name 52 | $tenantId = $Tenant.Id 53 | 54 | Write-Host ("Connected to Tenant {0} ({1}) as account '{2}'. Domain is '{3}'" -f $Tenant.DisplayName, $Tenant.Id, $currentUserPrincipalName, $verifiedDomainName) 55 | 56 | # Removes the applications 57 | Write-Host "Cleaning-up applications from tenant '$tenantId'" 58 | 59 | Write-Host "Removing 'client' (WinUI-App-Calling-MSGraph) if needed" 60 | try 61 | { 62 | Get-MgApplication -Filter "DisplayName eq 'WinUI-App-Calling-MSGraph'" | ForEach-Object {Remove-MgApplication -ApplicationId $_.Id } 63 | } 64 | catch 65 | { 66 | $message = $_ 67 | Write-Warning $Error[0] 68 | Write-Host "Unable to remove the application 'WinUI-App-Calling-MSGraph'. Error is $message. Try deleting manually." -ForegroundColor White -BackgroundColor Red 69 | } 70 | 71 | Write-Host "Making sure there are no more (WinUI-App-Calling-MSGraph) applications found, will remove if needed..." 72 | $apps = Get-MgApplication -Filter "DisplayName eq 'WinUI-App-Calling-MSGraph'" | Format-List Id, DisplayName, AppId, SignInAudience, PublisherDomain 73 | 74 | if ($apps) 75 | { 76 | Remove-MgApplication -ApplicationId $apps.Id 77 | } 78 | 79 | foreach ($app in $apps) 80 | { 81 | Remove-MgApplication -ApplicationId $app.Id 82 | Write-Host "Removed WinUI-App-Calling-MSGraph.." 83 | } 84 | 85 | # also remove service principals of this app 86 | try 87 | { 88 | Get-MgServicePrincipal -filter "DisplayName eq 'WinUI-App-Calling-MSGraph'" | ForEach-Object {Remove-MgServicePrincipal -ServicePrincipalId $_.Id -Confirm:$false} 89 | } 90 | catch 91 | { 92 | $message = $_ 93 | Write-Warning $Error[0] 94 | Write-Host "Unable to remove ServicePrincipal 'WinUI-App-Calling-MSGraph'. Error is $message. Try deleting manually from Enterprise applications." -ForegroundColor White -BackgroundColor Red 95 | } 96 | } 97 | 98 | # Pre-requisites 99 | if ($null -eq (Get-Module -ListAvailable -Name "Microsoft.Graph")) { 100 | Install-Module "Microsoft.Graph" -Scope CurrentUser 101 | } 102 | 103 | #Import-Module Microsoft.Graph 104 | 105 | if ($null -eq (Get-Module -ListAvailable -Name "Microsoft.Graph.Authentication")) { 106 | Install-Module "Microsoft.Graph.Authentication" -Scope CurrentUser 107 | } 108 | 109 | Import-Module Microsoft.Graph.Authentication 110 | 111 | if ($null -eq (Get-Module -ListAvailable -Name "Microsoft.Graph.Identity.DirectoryManagement")) { 112 | Install-Module "Microsoft.Graph.Identity.DirectoryManagement" -Scope CurrentUser 113 | } 114 | 115 | Import-Module Microsoft.Graph.Identity.DirectoryManagement 116 | 117 | if ($null -eq (Get-Module -ListAvailable -Name "Microsoft.Graph.Applications")) { 118 | Install-Module "Microsoft.Graph.Applications" -Scope CurrentUser 119 | } 120 | 121 | Import-Module Microsoft.Graph.Applications 122 | 123 | if ($null -eq (Get-Module -ListAvailable -Name "Microsoft.Graph.Groups")) { 124 | Install-Module "Microsoft.Graph.Groups" -Scope CurrentUser 125 | } 126 | 127 | Import-Module Microsoft.Graph.Groups 128 | 129 | if ($null -eq (Get-Module -ListAvailable -Name "Microsoft.Graph.Users")) { 130 | Install-Module "Microsoft.Graph.Users" -Scope CurrentUser 131 | } 132 | 133 | Import-Module Microsoft.Graph.Users 134 | 135 | $ErrorActionPreference = "Stop" 136 | 137 | 138 | try 139 | { 140 | Cleanup -tenantId $tenantId -environment $azureEnvironmentName 141 | } 142 | catch 143 | { 144 | $_.Exception.ToString() | out-host 145 | $message = $_ 146 | Write-Warning $Error[0] 147 | Write-Host "Unable to register apps. Error is $message." -ForegroundColor White -BackgroundColor Red 148 | } 149 | 150 | Write-Host "Disconnecting from tenant" 151 | Disconnect-MgGraph 152 | -------------------------------------------------------------------------------- /AppCreationScripts/Configure.ps1: -------------------------------------------------------------------------------- 1 | 2 | [CmdletBinding()] 3 | param( 4 | [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')] 5 | [string] $tenantId, 6 | [Parameter(Mandatory=$False, HelpMessage='Azure environment to use while running the script. Default = Global')] 7 | [string] $azureEnvironmentName 8 | ) 9 | 10 | <# 11 | This script creates the Azure AD applications needed for this sample and updates the configuration files 12 | for the visual Studio projects from the data in the Azure AD applications. 13 | 14 | In case you don't have Microsoft.Graph.Applications already installed, the script will automatically install it for the current user 15 | 16 | There are two ways to run this script. For more information, read the AppCreationScripts.md file in the same folder as this script. 17 | #> 18 | 19 | # Adds the requiredAccesses (expressed as a pipe separated string) to the requiredAccess structure 20 | # The exposed permissions are in the $exposedPermissions collection, and the type of permission (Scope | Role) is 21 | # described in $permissionType 22 | Function AddResourcePermission($requiredAccess, ` 23 | $exposedPermissions, [string]$requiredAccesses, [string]$permissionType) 24 | { 25 | foreach($permission in $requiredAccesses.Trim().Split("|")) 26 | { 27 | foreach($exposedPermission in $exposedPermissions) 28 | { 29 | if ($exposedPermission.Value -eq $permission) 30 | { 31 | $resourceAccess = New-Object Microsoft.Graph.PowerShell.Models.MicrosoftGraphResourceAccess 32 | $resourceAccess.Type = $permissionType # Scope = Delegated permissions | Role = Application permissions 33 | $resourceAccess.Id = $exposedPermission.Id # Read directory data 34 | $requiredAccess.ResourceAccess += $resourceAccess 35 | } 36 | } 37 | } 38 | } 39 | 40 | # 41 | # Example: GetRequiredPermissions "Microsoft Graph" "Graph.Read|User.Read" 42 | # See also: http://stackoverflow.com/questions/42164581/how-to-configure-a-new-azure-ad-application-through-powershell 43 | Function GetRequiredPermissions([string] $applicationDisplayName, [string] $requiredDelegatedPermissions, [string]$requiredApplicationPermissions, $servicePrincipal) 44 | { 45 | # If we are passed the service principal we use it directly, otherwise we find it from the display name (which might not be unique) 46 | if ($servicePrincipal) 47 | { 48 | $sp = $servicePrincipal 49 | } 50 | else 51 | { 52 | $sp = Get-MgServicePrincipal -Filter "DisplayName eq '$applicationDisplayName'" 53 | } 54 | $appid = $sp.AppId 55 | $requiredAccess = New-Object Microsoft.Graph.PowerShell.Models.MicrosoftGraphRequiredResourceAccess 56 | $requiredAccess.ResourceAppId = $appid 57 | $requiredAccess.ResourceAccess = New-Object System.Collections.Generic.List[Microsoft.Graph.PowerShell.Models.MicrosoftGraphResourceAccess] 58 | 59 | # $sp.Oauth2Permissions | Select Id,AdminConsentDisplayName,Value: To see the list of all the Delegated permissions for the application: 60 | if ($requiredDelegatedPermissions) 61 | { 62 | AddResourcePermission $requiredAccess -exposedPermissions $sp.Oauth2PermissionScopes -requiredAccesses $requiredDelegatedPermissions -permissionType "Scope" 63 | } 64 | 65 | # $sp.AppRoles | Select Id,AdminConsentDisplayName,Value: To see the list of all the Application permissions for the application 66 | if ($requiredApplicationPermissions) 67 | { 68 | AddResourcePermission $requiredAccess -exposedPermissions $sp.AppRoles -requiredAccesses $requiredApplicationPermissions -permissionType "Role" 69 | } 70 | return $requiredAccess 71 | } 72 | 73 | 74 | <#.Description 75 | This function takes a string input as a single line, matches a key value and replaces with the replacement value 76 | #> 77 | Function UpdateLine([string] $line, [string] $value) 78 | { 79 | $index = $line.IndexOf(':') 80 | $lineEnd = '' 81 | 82 | if($line[$line.Length - 1] -eq ','){ $lineEnd = ',' } 83 | 84 | if ($index -ige 0) 85 | { 86 | $line = $line.Substring(0, $index+1) + " " + '"' + $value+ '"' + $lineEnd 87 | } 88 | return $line 89 | } 90 | 91 | <#.Description 92 | This function takes a dictionary of keys to search and their replacements and replaces the placeholders in a text file 93 | #> 94 | Function UpdateTextFile([string] $configFilePath, [System.Collections.HashTable] $dictionary) 95 | { 96 | $lines = Get-Content $configFilePath 97 | $index = 0 98 | while($index -lt $lines.Length) 99 | { 100 | $line = $lines[$index] 101 | foreach($key in $dictionary.Keys) 102 | { 103 | if ($line.Contains($key)) 104 | { 105 | $lines[$index] = UpdateLine $line $dictionary[$key] 106 | } 107 | } 108 | $index++ 109 | } 110 | 111 | Set-Content -Path $configFilePath -Value $lines -Force 112 | } 113 | 114 | <#.Description 115 | This function takes a string as input and creates an instance of an Optional claim object 116 | #> 117 | Function CreateOptionalClaim([string] $name) 118 | { 119 | <#.Description 120 | This function creates a new Azure AD optional claims with default and provided values 121 | #> 122 | 123 | $appClaim = New-Object Microsoft.Graph.PowerShell.Models.MicrosoftGraphOptionalClaim 124 | $appClaim.AdditionalProperties = New-Object System.Collections.Generic.List[string] 125 | $appClaim.Source = $null 126 | $appClaim.Essential = $false 127 | $appClaim.Name = $name 128 | return $appClaim 129 | } 130 | 131 | <#.Description 132 | Primary entry method to create and configure app registrations 133 | #> 134 | Function ConfigureApplications 135 | { 136 | $isOpenSSl = 'N' #temporary disable open certificate creation 137 | 138 | <#.Description 139 | This function creates the Azure AD applications for the sample in the provided Azure AD tenant and updates the 140 | configuration files in the client and service project of the visual studio solution (App.Config and Web.Config) 141 | so that they are consistent with the Applications parameters 142 | #> 143 | 144 | if (!$azureEnvironmentName) 145 | { 146 | $azureEnvironmentName = "Global" 147 | } 148 | 149 | # Connect to the Microsoft Graph API, non-interactive is not supported for the moment (Oct 2021) 150 | Write-Host "Connecting to Microsoft Graph" 151 | if ($tenantId -eq "") { 152 | Connect-MgGraph -Scopes "User.Read.All Organization.Read.All Application.ReadWrite.All" -Environment $azureEnvironmentName 153 | } 154 | else { 155 | Connect-MgGraph -TenantId $tenantId -Scopes "User.Read.All Organization.Read.All Application.ReadWrite.All" -Environment $azureEnvironmentName 156 | } 157 | 158 | $context = Get-MgContext 159 | $tenantId = $context.TenantId 160 | 161 | # Get the user running the script 162 | $currentUserPrincipalName = $context.Account 163 | $user = Get-MgUser -Filter "UserPrincipalName eq '$($context.Account)'" 164 | 165 | # get the tenant we signed in to 166 | $Tenant = Get-MgOrganization 167 | $tenantName = $Tenant.DisplayName 168 | 169 | $verifiedDomain = $Tenant.VerifiedDomains | where {$_.Isdefault -eq $true} 170 | $verifiedDomainName = $verifiedDomain.Name 171 | $tenantId = $Tenant.Id 172 | 173 | Write-Host ("Connected to Tenant {0} ({1}) as account '{2}'. Domain is '{3}'" -f $Tenant.DisplayName, $Tenant.Id, $currentUserPrincipalName, $verifiedDomainName) 174 | 175 | # Create the client AAD application 176 | Write-Host "Creating the AAD application (WinUI-App-Calling-MSGraph)" 177 | # create the application 178 | $clientAadApplication = New-MgApplication -DisplayName "WinUI-App-Calling-MSGraph" ` 179 | -PublicClient ` 180 | @{ ` 181 | } ` 182 | -SignInAudience AzureADMyOrg ` 183 | #end of command 184 | 185 | $currentAppId = $clientAadApplication.AppId 186 | $currentAppObjectId = $clientAadApplication.Id 187 | 188 | $replyUrlsForApp = "ms-appx-web://microsoft.aad.brokerplugin/$currentAppId" 189 | Update-MgApplication -ApplicationId $currentAppObjectId -PublicClient @{RedirectUris=$replyUrlsForApp} 190 | $tenantName = (Get-MgApplication -ApplicationId $currentAppObjectId).PublisherDomain 191 | #Update-MgApplication -ApplicationId $currentAppObjectId -IdentifierUris @("https://$tenantName/WinUI-App-Calling-MSGraph") 192 | 193 | # create the service principal of the newly created application 194 | $clientServicePrincipal = New-MgServicePrincipal -AppId $currentAppId -Tags {WindowsAzureActiveDirectoryIntegratedApp} 195 | 196 | # add the user running the script as an app owner if needed 197 | $owner = Get-MgApplicationOwner -ApplicationId $currentAppObjectId 198 | if ($owner -eq $null) 199 | { 200 | New-MgApplicationOwnerByRef -ApplicationId $currentAppObjectId -BodyParameter = @{"@odata.id" = "htps://graph.microsoft.com/v1.0/directoryObjects/$user.ObjectId"} 201 | Write-Host "'$($user.UserPrincipalName)' added as an application owner to app '$($clientServicePrincipal.DisplayName)'" 202 | } 203 | 204 | # Add Claims 205 | 206 | $optionalClaims = New-Object Microsoft.Graph.PowerShell.Models.MicrosoftGraphOptionalClaims 207 | $optionalClaims.AccessToken = New-Object System.Collections.Generic.List[Microsoft.Graph.PowerShell.Models.MicrosoftGraphOptionalClaim] 208 | $optionalClaims.IdToken = New-Object System.Collections.Generic.List[Microsoft.Graph.PowerShell.Models.MicrosoftGraphOptionalClaim] 209 | $optionalClaims.Saml2Token = New-Object System.Collections.Generic.List[Microsoft.Graph.PowerShell.Models.MicrosoftGraphOptionalClaim] 210 | 211 | # Add Optional Claims 212 | 213 | $newClaim = CreateOptionalClaim -name "acct" 214 | $optionalClaims.IdToken += ($newClaim) 215 | Update-MgApplication -ApplicationId $currentAppObjectId -OptionalClaims $optionalClaims 216 | Write-Host "Done creating the client application (WinUI-App-Calling-MSGraph)" 217 | 218 | # URL of the AAD application in the Azure portal 219 | # Future? $clientPortalUrl = "https://portal.azure.com/#@"+$tenantName+"/blade/Microsoft_AAD_RegisteredApps/ApplicationMenuBlade/Overview/appId/"+$currentAppId+"/objectId/"+$currentAppObjectId+"/isMSAApp/" 220 | $clientPortalUrl = "https://portal.azure.com/#blade/Microsoft_AAD_RegisteredApps/ApplicationMenuBlade/CallAnAPI/appId/"+$currentAppId+"/objectId/"+$currentAppObjectId+"/isMSAApp/" 221 | 222 | Add-Content -Value "