├── .gitignore ├── LICENSE ├── README.md ├── img ├── auth-code-flow-1.png ├── auth-code-flow-2.png ├── auth-code-flow-3.png ├── auth-code-flow-4.png └── auth-code-flow-5.png ├── setup-scripts ├── install-azure-prerequisites.ps1 ├── new-app-registration.ps1 ├── new-app-serviceprincipal.ps1 └── new-rbac-groups.ps1 ├── web-api ├── Controllers │ └── TestController.cs ├── MsalAuthorizationCodeFlowApi.csproj ├── MsalAuthorizationCodeFlowApi.sln ├── Program.cs ├── Properties │ └── launchSettings.json ├── Startup.cs ├── appsettings.Development.json └── appsettings.json └── web-client ├── .env ├── .env.development ├── .env.production ├── .gitignore ├── README.md ├── package-lock.json ├── package.json ├── public ├── favicon.ico ├── index.html ├── logo192.png ├── logo512.png ├── manifest.json └── robots.txt ├── src ├── Components │ ├── App │ │ ├── App.css │ │ ├── App.tsx │ │ ├── IAppProps.tsx │ │ └── IAppState.tsx │ ├── AuthFailure │ │ ├── AuthFailure.tsx │ │ └── IAuthFailureProps.tsx │ ├── NotSignedIn │ │ ├── INotSignedInProps.tsx │ │ └── NotSignedIn.tsx │ └── SignedIn │ │ ├── ISignedInProps.tsx │ │ ├── SignedIn.css │ │ └── SignedIn.tsx ├── Services │ ├── ApiService.tsx │ ├── AppSettingsService.tsx │ └── AuthService.tsx ├── index.css ├── index.tsx ├── react-app-env.d.ts └── setupTests.ts └── tsconfig.json /.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 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Keith Babinec 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SampleMsalAuthorizationCodeFlow 2 | An example project to demonstrate the OAuth 2.0 authorization code flow against a protected web api resource with RBAC roles. 3 | 4 | ## Auth Scenario 5 | * Client: React SPA with Typescript, leveraging MSAL.JS 2.0 6 | * API: ASP.NET Core Web API 3.x 7 | * Azure AD: Single app registration with RBAC roles 8 | 9 | ## Tutorial Post 10 | 11 | For an end-to-end walkthrough and frequently asked questions, visit the linked blog post: https://keithbabinec.com/2020/09/27/oauth-2-0-authorization-code-flow-with-a-react-spa-asp-net-core-web-api-rbac-roles-and-msal 12 | 13 | ## Azure AD configuration 14 | 15 | These steps are required before you can build and run the application. All steps are to be executed from a PowerShell prompt. 16 | 17 | 1. Install Azure CLI tooling: [install-azure-prerequisites.ps1](setup-scripts/install-azure-prerequisites.ps1) 18 | ```powershell 19 | install-azure-prerequisites.ps1 20 | ``` 21 | 22 | 2. Configure application RBAC groups: [new-rbac-groups.ps1](setup-scripts/new-rbac-groups.ps1) 23 | ```powershell 24 | new-rbac-groups.ps1 -RbacGroupNames 'MyAppUsersGroup','MyAppAdministratorsGroup' 25 | ``` 26 | 27 | 3. Create Azure AD app registration: [new-app-registration.ps1](setup-scripts/new-app-registration.ps1) 28 | ```powershell 29 | new-app-registration.ps1 -AppRegistrationName 'authorization-flow-test-app' -RbacRoleNames 'MyAppUsersRole','MyAppAdministratorsRole' 30 | ``` 31 | 32 | 4. Create Azure AD app service principal: [new-app-serviceprincipal.ps1](setup-scripts/new-app-serviceprincipal.ps1) 33 | ```powershell 34 | new-app-serviceprincipal.ps1 -AppRegistrationName 'authorization-flow-test-app' 35 | ``` 36 | 37 | The following additional manual steps are required because no reasonable Azure tooling operation exists (yet) or they require more environment specific information. 38 | 39 | 5. In **Azure AD Groups**, add at least one user to each of the role groups created in step 2. 40 | 41 | 6. In the **Azure AD app registration**, click on the **Authentication** page then add your redirect URI's. 42 | * These must be of type 'SPA' and not 'Web', otherwise the auth flow will fail. 43 | * At minimum, add your local debug URI: https://localhost:3000 -- but you can also add your production environment redirects here if you know what they will be. 44 | 45 | 7. In the **Azure AD app registration**, click on the **Expose an API** page then take note of **scope** defined by the API. 46 | * There should be a default 'user_impersonation' scope created if you ran the script from step 4. 47 | * Copy the scope URI because it will be used in the MSAL app config later. 48 | 49 | 8. In the **Azure AD app service principal** (enterprise application), click on the **Properties** page, then set the **User Assignment Required** field to Yes. 50 | * This must be set to enforce authorized access to your client app. 51 | 52 | 9. In the **Azure AD app service principal** (enterprise application), click on the **Users and Groups** page, then assign users or groups to the custom app roles you have defined. 53 | 54 | ## Build and Run: Web API 55 | 56 | 1. Restore nuget packages. 57 | 58 | 2. Update [appsettings.json](web-api/appsettings.json) and [appsettings.Development.json](web-api/appsettings.Development.json) with the Azure AD app registration details from the above setup. 59 | 60 | 3. Launch the project, take note of the locally hosted URI. 61 | 62 | 4. Test that the endpoints are available. 63 | * Open a PowerShell prompt and send a test request against each of the 3 endpoints in the sample project. 64 | * Replace the URI below with the specific port from your machine. The following shows the responses you should expect to see without specifying auth headers: 65 | 66 | ```powershell 67 | Invoke-RestMethod -Uri https://localhost:44313/api/test/noauth -Method Get 68 | # should return: Successfully called the api/test/noauth endpoint, as an unauthenticated/anonymous user. 69 | 70 | Invoke-RestMethod -Uri https://localhost:44313/api/test/standard -Method Get 71 | # should return: Invoke-RestMethod: Response status code does not indicate success: 401 (Unauthorized). 72 | 73 | Invoke-RestMethod -Uri https://localhost:44313/api/test/admin -Method Get 74 | # should return: Invoke-RestMethod: Response status code does not indicate success: 401 (Unauthorized). 75 | ``` 76 | 77 | ## Build and Run: Web Client 78 | 79 | 1. Restore NPM packages 80 | ``` 81 | npm install 82 | ``` 83 | 84 | 2. Update [.env.development](web-client/.env.development) and [.env.production](web-client/.env.production) with the Azure AD app registration details from the above setup. 85 | 86 | 3. Start the project with local debugging. 87 | ``` 88 | npm start 89 | ``` 90 | 91 | 4. When the application starts in the browser: 92 | * Click the 'login' button, which will redirect you to the Microsoft Identity platform to sign in. 93 | * Sign in with a user that has been assigned to one of your app roles. 94 | * Upon redirect you should see buttons to invoke the 3 test web api endpoints. 95 | * Invoke the test endpoints to validate the end-to-end flow. 96 | 97 | ## Screenshots 98 | 99 | ![auth-code-flow-1](img/auth-code-flow-1.png) 100 | 101 | ![auth-code-flow-2](img/auth-code-flow-2.png) 102 | 103 | ![auth-code-flow-3](img/auth-code-flow-3.png) 104 | 105 | ![auth-code-flow-4](img/auth-code-flow-4.png) 106 | 107 | ![auth-code-flow-5](img/auth-code-flow-5.png) -------------------------------------------------------------------------------- /img/auth-code-flow-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/keithbabinec/SampleMsalAuthorizationCodeFlow/e7a3cf4b690f5651cdb449f665aee63f4a90171d/img/auth-code-flow-1.png -------------------------------------------------------------------------------- /img/auth-code-flow-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/keithbabinec/SampleMsalAuthorizationCodeFlow/e7a3cf4b690f5651cdb449f665aee63f4a90171d/img/auth-code-flow-2.png -------------------------------------------------------------------------------- /img/auth-code-flow-3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/keithbabinec/SampleMsalAuthorizationCodeFlow/e7a3cf4b690f5651cdb449f665aee63f4a90171d/img/auth-code-flow-3.png -------------------------------------------------------------------------------- /img/auth-code-flow-4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/keithbabinec/SampleMsalAuthorizationCodeFlow/e7a3cf4b690f5651cdb449f665aee63f4a90171d/img/auth-code-flow-4.png -------------------------------------------------------------------------------- /img/auth-code-flow-5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/keithbabinec/SampleMsalAuthorizationCodeFlow/e7a3cf4b690f5651cdb449f665aee63f4a90171d/img/auth-code-flow-5.png -------------------------------------------------------------------------------- /setup-scripts/install-azure-prerequisites.ps1: -------------------------------------------------------------------------------- 1 | [CmdletBinding()] 2 | param 3 | ( 4 | ) 5 | 6 | #Requires -RunAsAdministrator 7 | 8 | $ErrorActionPreference = "Stop" 9 | 10 | Write-Host "Checking for Azure CLI tooling prerequisite." 11 | 12 | # install the Azure CLI tools 13 | 14 | try 15 | { 16 | $null = az --version 17 | $cliToolsInstalled = $true 18 | } 19 | catch [System.Management.Automation.CommandNotFoundException] 20 | { 21 | $cliToolsInstalled = $false 22 | } 23 | 24 | if ($cliToolsInstalled -eq $false) 25 | { 26 | Write-Host "Azure CLI tooling was not found. Installing the latest version now." 27 | 28 | Write-Host "Downloading Azure CLI installer." 29 | Invoke-WebRequest -Uri https://aka.ms/installazurecliwindows -OutFile .\AzureCLI.msi 30 | 31 | Write-Host "Running Azure CLI installer." 32 | Start-Process msiexec.exe -Wait -ArgumentList '/I AzureCLI.msi /quiet' 33 | 34 | Write-Host "Removing Azure CLI installer file." 35 | Remove-Item .\AzureCLI.msi 36 | 37 | Write-Host "Installation completed. You should restart PowerShell to ensure the 'az' commands are available in the path." 38 | } 39 | else 40 | { 41 | Write-Host 'Azure CLI tooling is already installed.' 42 | } 43 | -------------------------------------------------------------------------------- /setup-scripts/new-app-registration.ps1: -------------------------------------------------------------------------------- 1 | [CmdletBinding()] 2 | param 3 | ( 4 | [Parameter( 5 | Mandatory=$true, 6 | HelpMessage="Specify the Azure AD app registration name. Example: test-authorization-flow-app")] 7 | [System.String] 8 | $AppRegistrationName, 9 | 10 | [Parameter( 11 | Mandatory=$true, 12 | HelpMessage="Specify the Azure AD RBAC role names to use in the app manifest. For example: MyAppUsersRole and MyAppAdministratorsRole.")] 13 | [System.String[]] 14 | $RbacRoleNames, 15 | 16 | [Parameter(Mandatory=$false)] 17 | [System.String] 18 | $AppHomePageUrl = "https://localhost:3000" 19 | ) 20 | 21 | $ErrorActionPreference = "Stop" 22 | 23 | $accounts = az account list 24 | if ($accounts -contains "az login") 25 | { 26 | Write-Host "Logging into Azure for the Azure CLI tooling." 27 | az login --allow-no-subscriptions 28 | } 29 | else 30 | { 31 | Write-Host "Already logged into Azure CLI tooling." 32 | } 33 | 34 | Write-Host "Checking to see if the Azure AD app registration ($AppRegistrationName) already exists." 35 | 36 | $cliEmptyResult = "[]" 37 | $appRegistration = az ad app list --display-name $AppRegistrationName 38 | 39 | if ($appRegistration -eq $cliEmptyResult) 40 | { 41 | Write-Host "App registration doesn't exist. Creating it now." 42 | 43 | # 'native-app' in this case means public client. 44 | 45 | $newAppRegistrationResult = az ad app create ` 46 | --display-name $AppRegistrationName ` 47 | --available-to-other-tenants false ` 48 | --homepage $AppHomePageUrl ` 49 | --native-app false 50 | 51 | Write-Host "Successfull created new app registration: $($appRegistration.appId)" 52 | 53 | $appRegistration = ConvertFrom-Json -InputObject ($newAppRegistrationResult | Out-String) 54 | 55 | # setting implicit flow to disabled on the new app request doesn't actually shut this off 56 | # for the token. make a second call to update the app manifest just for this property. 57 | 58 | Write-Host "Setting manifest property: oauth2AllowImplicitFlow=false" 59 | $null = az ad app update --id $appRegistration.appId --set oauth2AllowImplicitFlow=false 60 | 61 | Write-Host "Setting manifest property: oauth2AllowIdTokenImplicitFlow=false" 62 | $null = az ad app update --id $appRegistration.appId --set oauth2AllowIdTokenImplicitFlow=false 63 | 64 | $appIdUri = 'api://{0}' -f $appRegistration.appId 65 | Write-Host "Setting App ID Uri: $appIdUri" 66 | # note this also adds a default app scope: user_impersonation 67 | $null = az ad app update --id $appRegistration.appId --identifier-uris $appIdUri 68 | 69 | Write-Host "Adding RBAC roles to the application manifest." 70 | $roleObjects = New-Object -TypeName 'System.Collections.Generic.List[PSCustomObject]' 71 | 72 | foreach ($roleName in $RbacRoleNames) 73 | { 74 | $newRole = [PSCustomObject]@{ 75 | allowedMemberTypes = @("User") 76 | description = $roleName 77 | displayName = $roleName 78 | isEnabled = "true" 79 | value = $roleName 80 | } 81 | 82 | $roleObjects.Add($newRole) 83 | } 84 | 85 | $roleObjects | ConvertTo-Json | Out-File .\manifest-roles.json 86 | $null = az ad app update --id $appRegistration.appId --app-roles @manifest-roles.json 87 | Remove-Item -Path .\manifest-roles.json 88 | 89 | Write-Host "App registration setup completed." 90 | 91 | Write-Host "ACTION REQUIRED: In the Azure AD app registration, click on the Authentication page then add at least one redirect URI of type SPA" 92 | } 93 | else 94 | { 95 | Write-Host "App registration already exists. Creation will be skipped." 96 | } 97 | -------------------------------------------------------------------------------- /setup-scripts/new-app-serviceprincipal.ps1: -------------------------------------------------------------------------------- 1 | [CmdletBinding()] 2 | param 3 | ( 4 | [Parameter( 5 | Mandatory=$true, 6 | HelpMessage="Specify the Azure AD app registration name. Example: test-authorization-flow-app")] 7 | [System.String] 8 | $AppRegistrationName 9 | ) 10 | 11 | $ErrorActionPreference = "Stop" 12 | 13 | $accounts = az account list 14 | if ($accounts -contains "az login") 15 | { 16 | Write-Host "Logging into Azure for the Azure CLI tooling." 17 | az login --allow-no-subscriptions 18 | } 19 | else 20 | { 21 | Write-Host "Already logged into Azure CLI tooling." 22 | } 23 | 24 | Write-Host "Checking to see if the Azure AD app service principal (enterprise application) $AppRegistrationName already exists." 25 | 26 | $cliEmptyResult = "[]" 27 | 28 | $appRegistration = az ad app list --display-name $AppRegistrationName 29 | if ($appRegistration -eq $cliEmptyResult) 30 | { 31 | throw "App registration $AppRegistrationName was not found. Please create this application first and then re-run this script." 32 | } 33 | 34 | $appRegistration = ConvertFrom-Json -InputObject ($appRegistration | Out-String) 35 | $appRegistrationId = $appRegistration.appId 36 | 37 | $appServicePrincipal = az ad sp list --display-name $AppRegistrationName 38 | if ($appServicePrincipal -eq $cliEmptyResult) 39 | { 40 | Write-Host "App service principal doesn't exist. Creating it now." 41 | 42 | az ad sp create --id $appRegistrationId 43 | 44 | Write-Host "App service principal setup completed." 45 | 46 | Write-Host "ACTION REQUIRED: In the Azure AD app service principal (enterprise application), click on the Properties page, then set the User Assignment Required field to Yes" 47 | Write-Host "ACTION REQUIRED: In the Azure AD app service principal (enterprise application), click on the Users and Groups page, then assign users or groups to the custom app roles you have defined" 48 | } 49 | else 50 | { 51 | Write-Host "App service principal already exists. Creation will be skipped." 52 | } -------------------------------------------------------------------------------- /setup-scripts/new-rbac-groups.ps1: -------------------------------------------------------------------------------- 1 | [CmdletBinding()] 2 | param 3 | ( 4 | [Parameter( 5 | Mandatory=$true, 6 | HelpMessage="Specify the Azure AD RBAC group names to create. For example: MyAppUsersGroup and MyAppAdministratorsGroup.")] 7 | [System.String[]] 8 | $RbacGroupNames 9 | ) 10 | 11 | $ErrorActionPreference = "Stop" 12 | 13 | $accounts = az account list 14 | if ($accounts -contains "az login") 15 | { 16 | Write-Host "Logging into Azure for the Azure CLI tooling." 17 | az login --allow-no-subscriptions 18 | } 19 | else 20 | { 21 | Write-Host "Already logged into Azure CLI tooling." 22 | } 23 | 24 | $cliEmptyResult = "[]" 25 | 26 | foreach ($groupName in $RbacGroupNames) 27 | { 28 | Write-Host "Checking if the Azure AD security group '$groupName' exists." 29 | 30 | $groupResult = az ad group list --display-name $groupName 31 | 32 | if ($groupResult -eq $cliEmptyResult) 33 | { 34 | Write-Host "Group doesn't exist, creating it now." 35 | $null = az ad group create --display-name $groupName --mail-nickname $groupName 36 | } 37 | else 38 | { 39 | Write-Host "Group already exists, creation will be skipped." 40 | } 41 | } 42 | 43 | Write-Host "Group setup has completed." 44 | Write-Host "ACTION REQUIRED: In Azure AD Groups, add at least one user to each of the role groups created." -------------------------------------------------------------------------------- /web-api/Controllers/TestController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading.Tasks; 3 | using Microsoft.AspNetCore.Authorization; 4 | using Microsoft.AspNetCore.Mvc; 5 | 6 | namespace MsalAuthorizationCodeFlowApi.Controllers 7 | { 8 | [Route("api/[controller]")] 9 | [ApiController] 10 | public class TestController : ControllerBase 11 | { 12 | // this is a sample endpoint that requires 'AdminUser' role access, 13 | // as defined in the AAD app registration manifest and assigned via AAD 14 | // users and groups. 15 | [HttpGet()] 16 | [Route("admin")] 17 | [Authorize(Roles = "MyAppAdministratorsRole")] 18 | public async Task> AdminRoleGet() 19 | { 20 | // simulate some activity then return a result. 21 | 22 | await Task.Delay(TimeSpan.FromMilliseconds(50)).ConfigureAwait(false); 23 | 24 | return Ok("Successfully called the api/test/admin endpoint, user has correct (admin) authorization."); 25 | } 26 | 27 | // this is a sample endpoint that requires 'StandardUser' role access, 28 | // as defined in the AAD app registration manifest and assigned via AAD 29 | // users and groups. 30 | [HttpGet()] 31 | [Route("standard")] 32 | [Authorize(Roles = "MyAppUsersRole")] 33 | public async Task> StandardRoleGet() 34 | { 35 | // simulate some activity then return a result. 36 | 37 | await Task.Delay(TimeSpan.FromMilliseconds(50)).ConfigureAwait(false); 38 | 39 | return Ok("Successfully called the api/test/standard endpoint, user has correct (standard) authorization."); 40 | } 41 | 42 | // this is a sample endpoint that requires no authentication at all. 43 | // it is wide open to the public internet. 44 | [HttpGet()] 45 | [Route("noauth")] 46 | public async Task> NoAuthGet() 47 | { 48 | // simulate some activity then return a result. 49 | 50 | await Task.Delay(TimeSpan.FromMilliseconds(50)).ConfigureAwait(false); 51 | 52 | return Ok("Successfully called the api/test/noauth endpoint, as an unauthenticated/anonymous user."); 53 | } 54 | } 55 | } -------------------------------------------------------------------------------- /web-api/MsalAuthorizationCodeFlowApi.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | netcoreapp3.1 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /web-api/MsalAuthorizationCodeFlowApi.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.30104.148 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MsalAuthorizationCodeFlowApi", "MsalAuthorizationCodeFlowApi.csproj", "{5D4BF30D-9CFA-4F0F-B7D2-B9EF9E7725D9}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {5D4BF30D-9CFA-4F0F-B7D2-B9EF9E7725D9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {5D4BF30D-9CFA-4F0F-B7D2-B9EF9E7725D9}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {5D4BF30D-9CFA-4F0F-B7D2-B9EF9E7725D9}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {5D4BF30D-9CFA-4F0F-B7D2-B9EF9E7725D9}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {55954131-C9CF-47FB-884D-D6C44D56E929} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /web-api/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Hosting; 2 | using Microsoft.Extensions.Hosting; 3 | 4 | namespace MsalAuthorizationCodeFlowApi 5 | { 6 | public class Program 7 | { 8 | public static void Main(string[] args) 9 | { 10 | CreateHostBuilder(args).Build().Run(); 11 | } 12 | 13 | public static IHostBuilder CreateHostBuilder(string[] args) => 14 | Host.CreateDefaultBuilder(args) 15 | .ConfigureWebHostDefaults(webBuilder => 16 | { 17 | webBuilder.UseStartup(); 18 | }); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /web-api/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:54861", 8 | "sslPort": 44313 9 | } 10 | }, 11 | "profiles": { 12 | "IIS Express": { 13 | "commandName": "IISExpress", 14 | "launchBrowser": true, 15 | "launchUrl": "", 16 | "environmentVariables": { 17 | "ASPNETCORE_ENVIRONMENT": "Development" 18 | } 19 | }, 20 | "MsalAuthorizationCodeFlowApi": { 21 | "commandName": "Project", 22 | "launchBrowser": true, 23 | "launchUrl": "", 24 | "applicationUrl": "https://localhost:5001;http://localhost:5000", 25 | "environmentVariables": { 26 | "ASPNETCORE_ENVIRONMENT": "Development" 27 | } 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /web-api/Startup.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Builder; 2 | using Microsoft.AspNetCore.Hosting; 3 | using Microsoft.Extensions.Configuration; 4 | using Microsoft.Extensions.DependencyInjection; 5 | using Microsoft.Extensions.Hosting; 6 | using Microsoft.Identity.Web; 7 | 8 | namespace MsalAuthorizationCodeFlowApi 9 | { 10 | public class Startup 11 | { 12 | public Startup(IConfiguration configuration) 13 | { 14 | Configuration = configuration; 15 | } 16 | 17 | public IConfiguration Configuration { get; } 18 | 19 | // This method gets called by the runtime. Use this method to add services to the container. 20 | public void ConfigureServices(IServiceCollection services) 21 | { 22 | // add authentication support (bearer token validation). 23 | // configuration values are pulled from "AzureAD" section of app settings config. 24 | // this uses Microsoft Identity platform (AAD v2.0). 25 | 26 | services.AddMicrosoftIdentityWebApiAuthentication(Configuration, "AzureAd"); 27 | 28 | // add authorization support. 29 | 30 | services.AddAuthorization(); 31 | 32 | services.AddControllers(); 33 | 34 | // add wide-open CORS. 35 | // this should be changed before deploying to production 36 | // to ensure that only your accepted origins can call the API. 37 | 38 | services.AddCors(o => o.AddPolicy("default", builder => 39 | { 40 | builder.AllowAnyOrigin() 41 | .AllowAnyMethod() 42 | .AllowAnyHeader(); 43 | })); 44 | } 45 | 46 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 47 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 48 | { 49 | if (env.IsDevelopment()) 50 | { 51 | app.UseDeveloperExceptionPage(); 52 | } 53 | else 54 | { 55 | app.UseHsts(); 56 | } 57 | 58 | app.UseCors("default"); 59 | app.UseHttpsRedirection(); 60 | app.UseRouting(); 61 | 62 | app.UseAuthentication(); 63 | app.UseAuthorization(); 64 | 65 | app.UseEndpoints(endpoints => 66 | { 67 | endpoints.MapControllers(); 68 | }); 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /web-api/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | }, 9 | "AzureAd": { 10 | "Instance": "https://login.windows.net", 11 | "ClientId": "-- use client ID of app registration --", 12 | "TenantId": "-- use Azure tenant (directory) ID --", 13 | "Audience": "api://[-- use client ID of app registration --]" 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /web-api/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | }, 9 | "AllowedHosts": "*", 10 | "AzureAd": { 11 | "Instance": "https://login.windows.net", 12 | "ClientId": "-- use client ID of app registration --", 13 | "TenantId": "-- use Azure tenant (directory) ID --", 14 | "Audience": "api://[-- use client ID of app registration --]" 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /web-client/.env: -------------------------------------------------------------------------------- 1 | // app settings base file (common to all environments) 2 | 3 | // IMPORTANT: do not store secret values in this file. 4 | // The file itself is checked into source control and you don't commit secrets to the repo. 5 | // Also the values used in this file will be injected into the client build output, meaning 6 | // it is fully visible to the client. 7 | 8 | HTTPS = true -------------------------------------------------------------------------------- /web-client/.env.development: -------------------------------------------------------------------------------- 1 | // development environment configuration 2 | // this config is used for local debugging (ex: npm start) 3 | 4 | // IMPORTANT: do not store secret values in this file. 5 | // The file itself is checked into source control and you don't commit secrets to the repo. 6 | // Also the values used in this file will be injected into the client build output, meaning 7 | // it is fully visible to the client. 8 | 9 | // NOTE: All configuration values referenced by the source code must be prefixed with 'REACT_APP'. 10 | 11 | // specify the target web API's base URI 12 | // --REPLACE THE ADDRESS WITH WHATEVER YOUR LOCAL ENDPOINT IS-- 13 | REACT_APP_WEB_API_BASE_URI = "https://localhost:[web-api-port]/api" 14 | 15 | // specify the Azure app registration's application/client ID. 16 | // --REPLACE THE EMPTY GUID HERE WITH YOUR AAD APP REGISTRATION CLIENT ID-- 17 | REACT_APP_MSAL_CLIENT_ID = "00000000-0000-0000-0000-000000000000" 18 | 19 | // specify the Azure app registration's scope URI. 20 | // --REPLACE THE EMPTY GUID HERE WITH YOUR AAD APP REGISTRATION CLIENT ID-- 21 | REACT_APP_MSAL_CLIENT_SCOPE = "api://00000000-0000-0000-0000-000000000000/user_impersonation" 22 | 23 | // specify the Azure tenant (directory) authority URI. 24 | // --REPLACE THE EMPTY GUID HERE WITH YOUR AAD TENANT ID-- 25 | REACT_APP_MSAL_TENANT_AUTHORITY_URI = "https://login.windows.net/00000000-0000-0000-0000-000000000000" 26 | 27 | // where we whould store the token cache. 28 | REACT_APP_MSAL_CACHE_LOCATION = "sessionStorage" 29 | 30 | // set this to true if your users must use IE or EdgeBrowser (to help with redirect loop issues) 31 | REACT_APP_MSAL_AUTH_STATE_IN_COOKIE = "false" 32 | 33 | // set this to the web app post login page/url. 34 | REACT_APP_MSAL_LOGIN_REDIRECT_URI = "https://localhost:3000" -------------------------------------------------------------------------------- /web-client/.env.production: -------------------------------------------------------------------------------- 1 | // production environment configuration 2 | // this config is used for the production build output (ex: npm build) 3 | 4 | // IMPORTANT: do not store secret values in this file. 5 | // The file itself is checked into source control and you don't commit secrets to the repo. 6 | // Also the values used in this file will be injected into the client build output, meaning 7 | // it is fully visible to the client. 8 | 9 | // NOTE: All configuration values referenced by the source code must be prefixed with 'REACT_APP'. 10 | 11 | // specify the target web API's base URI 12 | // --REPLACE THE ADDRESS WITH WHATEVER YOUR PRODUCTION ENDPOINT IS-- 13 | REACT_APP_WEB_API_BASE_URI = "https://[my-website-api].azurewebsites.net/api/" 14 | 15 | // specify the Azure app registration's application/client ID. 16 | // --REPLACE THE EMPTY GUID HERE WITH YOUR AAD APP REGISTRATION CLIENT ID-- 17 | REACT_APP_MSAL_CLIENT_ID = "00000000-0000-0000-0000-000000000000" 18 | 19 | // specify the Azure app registration's scope URI. 20 | // --REPLACE THE EMPTY GUID HERE WITH YOUR AAD APP REGISTRATION CLIENT ID-- 21 | REACT_APP_MSAL_CLIENT_SCOPE = "api://00000000-0000-0000-0000-000000000000/user_impersonation" 22 | 23 | // specify the Azure tenant (directory) authority URI. 24 | // --REPLACE THE EMPTY GUID HERE WITH YOUR AAD TENANT ID-- 25 | REACT_APP_MSAL_TENANT_AUTHORITY_URI = "https://login.windows.net/00000000-0000-0000-0000-000000000000" 26 | 27 | // where we whould store the token cache. 28 | REACT_APP_MSAL_CACHE_LOCATION = "sessionStorage" 29 | 30 | // set this to true if your users must use IE or EdgeBrowser (to help with redirect loop issues) 31 | REACT_APP_MSAL_AUTH_STATE_IN_COOKIE = "false" 32 | 33 | // set this to the web app post login page/url. 34 | REACT_APP_MSAL_LOGIN_REDIRECT_URI = "https://localhost:3000" -------------------------------------------------------------------------------- /web-client/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | -------------------------------------------------------------------------------- /web-client/README.md: -------------------------------------------------------------------------------- 1 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). 2 | 3 | ## Available Scripts 4 | 5 | In the project directory, you can run: 6 | 7 | ### `npm start` 8 | 9 | Runs the app in the development mode.
10 | Open [https://localhost:3000](https://localhost:3000) to view it in the browser. 11 | 12 | The page will reload if you make edits.
13 | You will also see any lint errors in the console. 14 | 15 | ### `npm test` 16 | 17 | Launches the test runner in the interactive watch mode.
18 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. 19 | 20 | ### `npm run build` 21 | 22 | Builds the app for production to the `build` folder.
23 | It correctly bundles React in production mode and optimizes the build for the best performance. 24 | 25 | The build is minified and the filenames include the hashes.
26 | Your app is ready to be deployed! 27 | 28 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. 29 | 30 | ### `npm run eject` 31 | 32 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!** 33 | 34 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. 35 | 36 | Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. 37 | 38 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. 39 | 40 | ## Learn More 41 | 42 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). 43 | 44 | To learn React, check out the [React documentation](https://reactjs.org/). 45 | -------------------------------------------------------------------------------- /web-client/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "web-client", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "@azure/msal-browser": "^2.0.2", 7 | "@testing-library/jest-dom": "^4.2.4", 8 | "@testing-library/react": "^9.5.0", 9 | "@testing-library/user-event": "^7.2.1", 10 | "@types/jest": "^24.9.1", 11 | "@types/node": "^12.12.54", 12 | "@types/react": "^16.9.46", 13 | "@types/react-dom": "^16.9.8", 14 | "axios": "^0.20.0", 15 | "react": "^16.13.1", 16 | "react-dom": "^16.13.1", 17 | "react-scripts": "3.4.3", 18 | "typescript": "^3.7.5" 19 | }, 20 | "scripts": { 21 | "start": "react-scripts start", 22 | "build": "react-scripts build", 23 | "test": "react-scripts test", 24 | "eject": "react-scripts eject" 25 | }, 26 | "eslintConfig": { 27 | "extends": "react-app" 28 | }, 29 | "browserslist": { 30 | "production": [ 31 | ">0.2%", 32 | "not dead", 33 | "not op_mini all" 34 | ], 35 | "development": [ 36 | "last 1 chrome version", 37 | "last 1 firefox version", 38 | "last 1 safari version" 39 | ] 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /web-client/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/keithbabinec/SampleMsalAuthorizationCodeFlow/e7a3cf4b690f5651cdb449f665aee63f4a90171d/web-client/public/favicon.ico -------------------------------------------------------------------------------- /web-client/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 27 | React App 28 | 29 | 30 | 31 |
32 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /web-client/public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/keithbabinec/SampleMsalAuthorizationCodeFlow/e7a3cf4b690f5651cdb449f665aee63f4a90171d/web-client/public/logo192.png -------------------------------------------------------------------------------- /web-client/public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/keithbabinec/SampleMsalAuthorizationCodeFlow/e7a3cf4b690f5651cdb449f665aee63f4a90171d/web-client/public/logo512.png -------------------------------------------------------------------------------- /web-client/public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | }, 10 | { 11 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /web-client/public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | Disallow: 4 | -------------------------------------------------------------------------------- /web-client/src/Components/App/App.css: -------------------------------------------------------------------------------- 1 | .App { 2 | text-align: center; 3 | } 4 | 5 | .App-header { 6 | background-color: #282c34; 7 | min-height: 100vh; 8 | display: flex; 9 | flex-direction: column; 10 | align-items: center; 11 | justify-content: center; 12 | font-size: calc(10px + 2vmin); 13 | color: white; 14 | } 15 | 16 | .App-link { 17 | color: #61dafb; 18 | } 19 | -------------------------------------------------------------------------------- /web-client/src/Components/App/App.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import IAppProps from './IAppProps'; 3 | import IAppState from './IAppState'; 4 | import './App.css'; 5 | import SignedIn from '../SignedIn/SignedIn'; 6 | import NotSignedIn from '../NotSignedIn/NotSignedIn'; 7 | 8 | class App extends React.Component { 9 | 10 | constructor(props: IAppProps) { 11 | super(props); 12 | 13 | this.state = { 14 | apiResult: '', 15 | apiError: '' 16 | } 17 | } 18 | 19 | invokeSignInEvent = () => { 20 | this.props.authServiceInstance.SignIn(); 21 | } 22 | 23 | invokeSignOutEvent = () => { 24 | this.props.authServiceInstance.SignOut(); 25 | } 26 | 27 | invokeUnauthenticatedApiCall = () => { 28 | this.props.apiService.InvokeNoAuthApiCall().then((response: any) => { 29 | this.setState({'apiResult': response, 'apiError': ''}); 30 | }).catch((error: any) => { 31 | this.setState({'apiResult': '', 'apiError': error.message}); 32 | }); 33 | } 34 | 35 | invokeUserEndpointApiCall = () => { 36 | this.props.apiService.InvokeUserApiCall().then((response: any) => { 37 | this.setState({'apiResult': response, 'apiError': ''}); 38 | }).catch((error: any) => { 39 | this.setState({'apiResult': '', 'apiError': error.message}); 40 | }); 41 | } 42 | 43 | invokeAdminEndpointApiCall = () => { 44 | this.props.apiService.InvokeAdminApiCall().then((response: any) => { 45 | this.setState({'apiResult': response, 'apiError': ''}); 46 | }).catch((error: any) => { 47 | this.setState({'apiResult': '', 'apiError': error.message}); 48 | }); 49 | } 50 | 51 | render() { 52 | if (this.props.authServiceInstance.account) { 53 | return ( 54 |
55 | 61 | { 62 | this.state.apiResult && 63 |
API Operation Output: {this.state.apiResult}
64 | } 65 | { 66 | this.state.apiError && 67 |
API Operation Error: {this.state.apiError}
68 | } 69 |
70 | ); 71 | } 72 | else { 73 | return ( 74 |
75 | 78 |
79 | ); 80 | } 81 | } 82 | } 83 | 84 | export default App; -------------------------------------------------------------------------------- /web-client/src/Components/App/IAppProps.tsx: -------------------------------------------------------------------------------- 1 | import ApiService from "../../Services/ApiService"; 2 | import AuthService from "../../Services/AuthService"; 3 | 4 | interface IAppProps { 5 | authServiceInstance: AuthService; 6 | apiService: ApiService; 7 | }; 8 | 9 | export default IAppProps; -------------------------------------------------------------------------------- /web-client/src/Components/App/IAppState.tsx: -------------------------------------------------------------------------------- 1 | interface IAppState { 2 | apiResult: string 3 | apiError: string 4 | }; 5 | 6 | export default IAppState; -------------------------------------------------------------------------------- /web-client/src/Components/AuthFailure/AuthFailure.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import IAuthFailureProps from './IAuthFailureProps'; 3 | 4 | class AuthFailure extends React.Component { 5 | render() { 6 | return ( 7 |
8 |

9 | {this.props.errorMessage} 10 |

11 |
12 | ); 13 | } 14 | } 15 | 16 | export default AuthFailure; -------------------------------------------------------------------------------- /web-client/src/Components/AuthFailure/IAuthFailureProps.tsx: -------------------------------------------------------------------------------- 1 | interface IAuthFailureProps { 2 | errorMessage: string; 3 | }; 4 | 5 | export default IAuthFailureProps; -------------------------------------------------------------------------------- /web-client/src/Components/NotSignedIn/INotSignedInProps.tsx: -------------------------------------------------------------------------------- 1 | import AuthService from "../../Services/AuthService"; 2 | 3 | interface INotSignedInProps { 4 | authServiceInstance: AuthService; 5 | loginButtonClicked: React.MouseEventHandler; 6 | }; 7 | 8 | export default INotSignedInProps; -------------------------------------------------------------------------------- /web-client/src/Components/NotSignedIn/NotSignedIn.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import INotSignedInProps from './INotSignedInProps'; 3 | 4 | class NotSignedIn extends React.Component { 5 | render() { 6 | return ( 7 |
8 |

9 | User is not logged in. 10 |

11 | 12 |
13 | ); 14 | } 15 | } 16 | 17 | export default NotSignedIn; -------------------------------------------------------------------------------- /web-client/src/Components/SignedIn/ISignedInProps.tsx: -------------------------------------------------------------------------------- 1 | import AuthService from "../../Services/AuthService"; 2 | 3 | interface ISignedInProps { 4 | authServiceInstance: AuthService; 5 | apiUnauthenticatedButtonClicked: React.MouseEventHandler; 6 | apiUserEndpointButtonClicked: React.MouseEventHandler; 7 | apiAdminEndpointButtonClicked: React.MouseEventHandler; 8 | logoutButtonClicked: React.MouseEventHandler; 9 | }; 10 | 11 | export default ISignedInProps; -------------------------------------------------------------------------------- /web-client/src/Components/SignedIn/SignedIn.css: -------------------------------------------------------------------------------- 1 | .buttonDiv { 2 | margin: 5px 3 | } -------------------------------------------------------------------------------- /web-client/src/Components/SignedIn/SignedIn.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ISignedInProps from './ISignedInProps'; 3 | import './SignedIn.css' 4 | 5 | class SignedIn extends React.Component { 6 | render() { 7 | return ( 8 |
9 |

10 | Logged in as user: {this.props.authServiceInstance.account?.username} 11 |

12 |
13 | 14 |
15 |
16 | 17 |
18 |
19 | 20 |
21 |
22 | 23 |
24 |
25 | ); 26 | } 27 | } 28 | 29 | export default SignedIn; -------------------------------------------------------------------------------- /web-client/src/Services/ApiService.tsx: -------------------------------------------------------------------------------- 1 | import { AuthenticationResult } from '@azure/msal-browser'; 2 | import axios, { AxiosInstance } from 'axios'; 3 | import AuthService from './AuthService'; 4 | 5 | class ApiService { 6 | 7 | // constructor that requires a base URI. 8 | constructor(baseUri: string, authService: AuthService) { 9 | if (!baseUri) { 10 | throw new Error('the base uri was not provided'); 11 | } 12 | if (!authService) { 13 | throw new Error('the auth service was not provided'); 14 | } 15 | 16 | this.AuthorizationService = authService; 17 | 18 | this.AuthenticatedApi = axios.create({ 19 | baseURL: baseUri, 20 | // will inject auth header on-demand later as needed. 21 | headers: { 22 | 'Content-Type': 'application/json', 23 | } 24 | }); 25 | } 26 | 27 | // the authenticated api 28 | AuthenticatedApi: AxiosInstance; 29 | 30 | // the authorization service 31 | // wrapper around MSAL 32 | AuthorizationService: AuthService; 33 | 34 | // an api operation that calls one of the anonymous / no-auth endpoints. 35 | InvokeNoAuthApiCall() { 36 | return this.AuthenticatedApi.get('/test/noauth') 37 | .then((response: any) => { 38 | return response.data; 39 | }) 40 | .catch((error: any) => { 41 | throw Error('An error has occurred calling the api: ' + error); 42 | }); 43 | } 44 | 45 | InvokeUserApiCall() { 46 | return this.AuthorizationService.GetToken() 47 | .then((response: AuthenticationResult) => { 48 | return this.AuthenticatedApi.get('/test/standard', { 49 | headers: { 50 | Authorization: 'Bearer ' + response.accessToken 51 | } 52 | }) 53 | .then((response: any) => { 54 | return response.data; 55 | }) 56 | .catch((error: any) => { 57 | throw Error('An error has occurred calling the web api: ' + error); 58 | }); 59 | }) 60 | .catch((error: any) => { 61 | throw Error('An error has occurred: ' + error); 62 | }); 63 | } 64 | 65 | // an api operation that calls one of the admin user authorized endpoints. 66 | InvokeAdminApiCall() { 67 | return this.AuthorizationService.GetToken() 68 | .then((response: AuthenticationResult) => { 69 | return this.AuthenticatedApi.get('/test/admin', { 70 | headers: { 71 | Authorization: 'Bearer ' + response.accessToken 72 | } 73 | }) 74 | .then((response: any) => { 75 | return response.data; 76 | }) 77 | .catch((error: any) => { 78 | throw Error('An error has occurred calling the web api: ' + error); 79 | }); 80 | }) 81 | .catch((error: any) => { 82 | throw Error('An error has occurred: ' + error); 83 | }); 84 | } 85 | } 86 | 87 | export default ApiService; -------------------------------------------------------------------------------- /web-client/src/Services/AppSettingsService.tsx: -------------------------------------------------------------------------------- 1 | class AppSettingsService { 2 | GetWebApiBaseUri(): string { 3 | return process.env.REACT_APP_WEB_API_BASE_URI as string; 4 | } 5 | GetMsalClientId(): string { 6 | return process.env.REACT_APP_MSAL_CLIENT_ID as string; 7 | } 8 | GetMsalClientScope(): string { 9 | return process.env.REACT_APP_MSAL_CLIENT_SCOPE as string; 10 | } 11 | GetMsalTenantAuthorityUri(): string { 12 | return process.env.REACT_APP_MSAL_TENANT_AUTHORITY_URI as string; 13 | } 14 | GetMsalCacheLocation(): string { 15 | return process.env.REACT_APP_MSAL_CACHE_LOCATION as string; 16 | } 17 | GetMsalStoreAuthInCookie(): boolean { 18 | let stringValue = process.env.REACT_APP_MSAL_AUTH_STATE_IN_COOKIE as string; 19 | 20 | if (stringValue.toLowerCase() === 'true') { 21 | return true; 22 | } 23 | else if (stringValue.toLowerCase() === 'false') { 24 | return false; 25 | } 26 | else { 27 | throw new Error('MSAL_AUTH_STATE_IN_COOKIE setting is not a valid boolean.'); 28 | } 29 | } 30 | GetLoginRedirectUri(): string { 31 | return process.env.REACT_APP_MSAL_LOGIN_REDIRECT_URI as string; 32 | } 33 | } 34 | 35 | export default AppSettingsService; -------------------------------------------------------------------------------- /web-client/src/Services/AuthService.tsx: -------------------------------------------------------------------------------- 1 | import AppSettingsService from './AppSettingsService'; 2 | import { AccountInfo, Configuration, AuthenticationResult, PublicClientApplication, SilentRequest, RedirectRequest, EndSessionRequest } from "@azure/msal-browser" 3 | 4 | class AuthService { 5 | 6 | constructor(appSettings: AppSettingsService) { 7 | if (!appSettings) { 8 | throw new Error('the app settings service was not provided'); 9 | } 10 | 11 | this.appSettings = appSettings; 12 | 13 | let msalConfig = this.GetMsalClientConfiguration(); 14 | this.msalApplication = new PublicClientApplication(msalConfig); 15 | } 16 | 17 | // msal application object 18 | msalApplication: PublicClientApplication; 19 | 20 | // settings service 21 | appSettings: AppSettingsService; 22 | 23 | // cached account info 24 | account?: AccountInfo; 25 | 26 | HandlePageLoadEvent(): Promise { 27 | // let exceptions bubble up to the caller to handle 28 | return this.msalApplication.handleRedirectPromise().then((authResult: AuthenticationResult | null) => { 29 | this.HandleRedirectResponse(authResult); 30 | }); 31 | } 32 | 33 | HandleRedirectResponse(authResult: AuthenticationResult | null): void { 34 | // if this page load is redirect from the Microsoft Identity platform then the 35 | // authResult will be populated. Otherwise null on other page loads. 36 | 37 | if (authResult !== null) { 38 | // save the fresh account info from the result. 39 | this.account = authResult.account; 40 | } 41 | else { 42 | // see if we have cached accounts. 43 | const currentAccounts = this.msalApplication.getAllAccounts(); 44 | 45 | if (currentAccounts === null) { 46 | // no cached accounts. 47 | // user will need to click the sign-in button and redirect to login. 48 | return; 49 | } 50 | else if (currentAccounts.length > 1) { 51 | // there are some situations where the user may have multiple (different) cached logins. 52 | // this code sample does not cover that scenario but just logs a warning here. 53 | // this conditional block would need to be updated to support multiple accounts. 54 | // otherwise it will just grab the first one below. 55 | console.warn("Multiple accounts detected in MSAL account cache."); 56 | this.account = currentAccounts[0]; 57 | } 58 | else if (currentAccounts.length === 1) { 59 | // we have exactly 1 cached account. 60 | // set the account info. user may not need to sign in. 61 | this.account = currentAccounts[0]; 62 | } 63 | } 64 | } 65 | 66 | GetMsalClientConfiguration(): Configuration { 67 | return { 68 | auth: { 69 | clientId: this.appSettings.GetMsalClientId(), 70 | authority: this.appSettings.GetMsalTenantAuthorityUri(), 71 | redirectUri: this.appSettings.GetLoginRedirectUri() 72 | }, 73 | cache: { 74 | cacheLocation: this.appSettings.GetMsalCacheLocation(), 75 | storeAuthStateInCookie: this.appSettings.GetMsalStoreAuthInCookie() 76 | } 77 | } 78 | } 79 | 80 | GetToken(): Promise { 81 | let tokenRequest: SilentRequest = { 82 | account: this.account as AccountInfo, 83 | scopes: [ this.appSettings.GetMsalClientScope() ] 84 | } 85 | 86 | // msal will return the cached token if present, or call to get a new one 87 | // if it is expired or near expiring. 88 | return this.msalApplication.acquireTokenSilent(tokenRequest); 89 | } 90 | 91 | SignIn() { 92 | let loginRedirectRequestPayload: RedirectRequest = { 93 | scopes: [ this.appSettings.GetMsalClientScope() ], 94 | prompt: "select_account" 95 | } 96 | 97 | // this will redirect the web application to the Microsoft Identity platform sign in pages. 98 | // no code will execute after this point. 99 | this.msalApplication.loginRedirect(loginRedirectRequestPayload); 100 | } 101 | 102 | SignOut() { 103 | if (!this.account) { 104 | // no cached login to signout 105 | return; 106 | } 107 | 108 | let accountInfo: AccountInfo | null = this.msalApplication.getAccountByUsername(this.account?.username as string); 109 | 110 | if (accountInfo !== null) { 111 | let logoutRequestPayload: EndSessionRequest = { 112 | account: accountInfo 113 | } 114 | 115 | this.msalApplication.logout(logoutRequestPayload) 116 | } 117 | } 118 | } 119 | 120 | export default AuthService; -------------------------------------------------------------------------------- /web-client/src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 4 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', 5 | sans-serif; 6 | -webkit-font-smoothing: antialiased; 7 | -moz-osx-font-smoothing: grayscale; 8 | } 9 | 10 | code { 11 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', 12 | monospace; 13 | } 14 | -------------------------------------------------------------------------------- /web-client/src/index.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import './index.css'; 4 | import App from './Components/App/App'; 5 | import AuthFailure from './Components/AuthFailure/AuthFailure'; 6 | import AuthService from './Services/AuthService'; 7 | import ApiService from './Services/ApiService'; 8 | import AppSettingsService from './Services/AppSettingsService'; 9 | 10 | // Security Warning: Be aware that this code sample uses the browser's sessionStorage to store tokens. 11 | // This means the token could be extracted if the site is vulnerable to an XSS attack or if 12 | // untrusted/malicious scripts are executed in your web app. Keep this in mind when using this authentication flow. 13 | 14 | let appSettings = new AppSettingsService(); 15 | let authService = new AuthService(appSettings); 16 | 17 | authService.HandlePageLoadEvent().then(() => { 18 | // auth flow was successful. 19 | // start the application now. 20 | 21 | let baseApiUri: string = appSettings.GetWebApiBaseUri(); 22 | let apiService: ApiService = new ApiService(baseApiUri, authService); 23 | 24 | ReactDOM.render(, document.getElementById('root')); 25 | }).catch((error) => { 26 | // auth flow has failed. 27 | // display an error instead of starting the main application. 28 | ReactDOM.render(, document.getElementById('root')); 29 | }); 30 | -------------------------------------------------------------------------------- /web-client/src/react-app-env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | -------------------------------------------------------------------------------- /web-client/src/setupTests.ts: -------------------------------------------------------------------------------- 1 | // jest-dom adds custom jest matchers for asserting on DOM nodes. 2 | // allows you to do things like: 3 | // expect(element).toHaveTextContent(/react/i) 4 | // learn more: https://github.com/testing-library/jest-dom 5 | import '@testing-library/jest-dom/extend-expect'; 6 | -------------------------------------------------------------------------------- /web-client/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "lib": [ 5 | "dom", 6 | "dom.iterable", 7 | "esnext" 8 | ], 9 | "allowJs": true, 10 | "skipLibCheck": true, 11 | "esModuleInterop": true, 12 | "allowSyntheticDefaultImports": true, 13 | "strict": true, 14 | "forceConsistentCasingInFileNames": true, 15 | "module": "esnext", 16 | "moduleResolution": "node", 17 | "resolveJsonModule": true, 18 | "isolatedModules": true, 19 | "noEmit": true, 20 | "jsx": "react" 21 | }, 22 | "include": [ 23 | "src" 24 | ] 25 | } 26 | --------------------------------------------------------------------------------