├── .gitattributes ├── .gitignore ├── Batch.txt ├── BestPractices.sln ├── BestPractices ├── AccessEvaluation.cs ├── Account.contrast-white.ico ├── App.config ├── App.xaml ├── App.xaml.cs ├── AppResults.cs ├── AppRole.cs ├── BatchResult.cs ├── BestPractices.csproj ├── CallRestAPIs.cs ├── GroupResults.cs ├── Logger.cs ├── MainWindow.xaml ├── MainWindow.xaml.cs ├── Properties │ ├── AssemblyInfo.cs │ ├── Resources.Designer.cs │ ├── Resources.resx │ ├── Settings.Designer.cs │ └── Settings.settings ├── RoleResults.cs ├── RolesAndGroupsTabData.cs ├── ServicePrincipalResults.cs ├── TokenCacheHelper.cs ├── TokenHandling.cs ├── TokenType.cs └── UserAccessEvaulationResults.cs ├── Images ├── 1.png ├── 2.png ├── 3.png ├── 4.png ├── 5.png └── 6.png └── README.md /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | x64/ 19 | x86/ 20 | bld/ 21 | [Bb]in/ 22 | [Oo]bj/ 23 | [Ll]og/ 24 | 25 | # Visual Studio 2015 cache/options directory 26 | .vs/ 27 | # Uncomment if you have tasks that create the project's static files in wwwroot 28 | #wwwroot/ 29 | 30 | # MSTest test Results 31 | [Tt]est[Rr]esult*/ 32 | [Bb]uild[Ll]og.* 33 | 34 | # NUNIT 35 | *.VisualState.xml 36 | TestResult.xml 37 | 38 | # Build Results of an ATL Project 39 | [Dd]ebugPS/ 40 | [Rr]eleasePS/ 41 | dlldata.c 42 | 43 | # DNX 44 | project.lock.json 45 | artifacts/ 46 | 47 | *_i.c 48 | *_p.c 49 | *_i.h 50 | *.ilk 51 | *.meta 52 | *.obj 53 | *.pch 54 | *.pdb 55 | *.pgc 56 | *.pgd 57 | *.rsp 58 | *.sbr 59 | *.tlb 60 | *.tli 61 | *.tlh 62 | *.tmp 63 | *.tmp_proj 64 | *.log 65 | *.vspscc 66 | *.vssscc 67 | .builds 68 | *.pidb 69 | *.svclog 70 | *.scc 71 | 72 | # Chutzpah Test files 73 | _Chutzpah* 74 | 75 | # Visual C++ cache files 76 | ipch/ 77 | *.aps 78 | *.ncb 79 | *.opendb 80 | *.opensdf 81 | *.sdf 82 | *.cachefile 83 | *.VC.db 84 | *.VC.VC.opendb 85 | 86 | # Visual Studio profiler 87 | *.psess 88 | *.vsp 89 | *.vspx 90 | *.sap 91 | 92 | # TFS 2012 Local Workspace 93 | $tf/ 94 | 95 | # Guidance Automation Toolkit 96 | *.gpState 97 | 98 | # ReSharper is a .NET coding add-in 99 | _ReSharper*/ 100 | *.[Rr]e[Ss]harper 101 | *.DotSettings.user 102 | 103 | # JustCode is a .NET coding add-in 104 | .JustCode 105 | 106 | # TeamCity is a build add-in 107 | _TeamCity* 108 | 109 | # DotCover is a Code Coverage Tool 110 | *.dotCover 111 | 112 | # NCrunch 113 | _NCrunch_* 114 | .*crunch*.local.xml 115 | nCrunchTemp_* 116 | 117 | # MightyMoose 118 | *.mm.* 119 | AutoTest.Net/ 120 | 121 | # Web workbench (sass) 122 | .sass-cache/ 123 | 124 | # Installshield output folder 125 | [Ee]xpress/ 126 | 127 | # DocProject is a documentation generator add-in 128 | DocProject/buildhelp/ 129 | DocProject/Help/*.HxT 130 | DocProject/Help/*.HxC 131 | DocProject/Help/*.hhc 132 | DocProject/Help/*.hhk 133 | DocProject/Help/*.hhp 134 | DocProject/Help/Html2 135 | DocProject/Help/html 136 | 137 | # Click-Once directory 138 | publish/ 139 | 140 | # Publish Web Output 141 | *.[Pp]ublish.xml 142 | *.azurePubxml 143 | # TODO: Comment the next line if you want to checkin your web deploy settings 144 | # but database connection strings (with potential passwords) will be unencrypted 145 | *.pubxml 146 | *.publishproj 147 | 148 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 149 | # checkin your Azure Web App publish settings, but sensitive information contained 150 | # in these scripts will be unencrypted 151 | PublishScripts/ 152 | 153 | # NuGet Packages 154 | *.nupkg 155 | # The packages folder can be ignored because of Package Restore 156 | **/packages/* 157 | # except build/, which is used as an MSBuild target. 158 | !**/packages/build/ 159 | # Uncomment if necessary however generally it will be regenerated when needed 160 | #!**/packages/repositories.config 161 | # NuGet v3's project.json files produces more ignoreable files 162 | *.nuget.props 163 | *.nuget.targets 164 | 165 | # Microsoft Azure Build Output 166 | csx/ 167 | *.build.csdef 168 | 169 | # Microsoft Azure Emulator 170 | ecf/ 171 | rcf/ 172 | 173 | # Windows Store app package directories and files 174 | AppPackages/ 175 | BundleArtifacts/ 176 | Package.StoreAssociation.xml 177 | _pkginfo.txt 178 | 179 | # Visual Studio cache files 180 | # files ending in .cache can be ignored 181 | *.[Cc]ache 182 | # but keep track of directories ending in .cache 183 | !*.[Cc]ache/ 184 | 185 | # Others 186 | ClientBin/ 187 | ~$* 188 | *~ 189 | *.dbmdl 190 | *.dbproj.schemaview 191 | *.pfx 192 | *.publishsettings 193 | node_modules/ 194 | orleans.codegen.cs 195 | 196 | # Since there are multiple workflows, uncomment next line to ignore bower_components 197 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 198 | #bower_components/ 199 | 200 | # RIA/Silverlight projects 201 | Generated_Code/ 202 | 203 | # Backup & report files from converting an old project file 204 | # to a newer Visual Studio version. Backup files are not needed, 205 | # because we have git ;-) 206 | _UpgradeReport_Files/ 207 | Backup*/ 208 | UpgradeLog*.XML 209 | UpgradeLog*.htm 210 | 211 | # SQL Server files 212 | *.mdf 213 | *.ldf 214 | 215 | # Business Intelligence projects 216 | *.rdl.data 217 | *.bim.layout 218 | *.bim_*.settings 219 | 220 | # Microsoft Fakes 221 | FakesAssemblies/ 222 | 223 | # GhostDoc plugin setting file 224 | *.GhostDoc.xml 225 | 226 | # Node.js Tools for Visual Studio 227 | .ntvs_analysis.dat 228 | 229 | # Visual Studio 6 build log 230 | *.plg 231 | 232 | # Visual Studio 6 workspace options file 233 | *.opt 234 | 235 | # Visual Studio LightSwitch build output 236 | **/*.HTMLClient/GeneratedArtifacts 237 | **/*.DesktopClient/GeneratedArtifacts 238 | **/*.DesktopClient/ModelManifest.xml 239 | **/*.Server/GeneratedArtifacts 240 | **/*.Server/ModelManifest.xml 241 | _Pvt_Extensions 242 | 243 | # Paket dependency manager 244 | .paket/paket.exe 245 | paket-files/ 246 | 247 | # FAKE - F# Make 248 | .fake/ 249 | 250 | # JetBrains Rider 251 | .idea/ 252 | *.sln.iml 253 | /1P.txt 254 | -------------------------------------------------------------------------------- /Batch.txt: -------------------------------------------------------------------------------- 1 | {"requests":[ 2 | {"id":"1","method":"GET","url":"/me?$select=signInSessionsValidFromDateTime,refreshTokensValidFromDateTime,deletedDateTime,accountEnabled"}, 3 | 4 | {"id":"2","dependsOn": [ "1" ],"method":"GET","url":"/servicePrincipals(appId='acaf6ce9-81f0-462a-a93d-a314070738d3')?$select=appRoles,appRoleAssignmentRequired,accountEnabled"}, 5 | 6 | {"id":"3","dependsOn": [ "2" ],"method":"GET","url":"/me/appRoleAssignments?$filter=resourceId eq 9ae2b746-8c8d-4cb7-afed-93a1f2fd9c9e"}, 7 | 8 | {"id":"4","dependsOn": [ "3" ],"method": "POST","url":"me/checkMemberObjects", 9 | "body":{"ids":["62e90394-69f5-4237-9190-012177145e10", 10 | "f2ef992c-3afb-46b9-b7cf-a126ee74c451", 11 | "fdd7a751-b60b-444a-984c-02652fe8fa1c", 12 | "cf1c38e5-3621-4004-a7cb-879624dced7c", 13 | "32055622-bbfb-467b-8214-98b01e0967bf", 14 | "b17b3ae9-67b6-43ef-8944-8b0e0c1b6cb3", 15 | "64b8ae64-f504-4853-b400-a217900fad56"]}, 16 | "headers":{"Content-Type":"application/json"}}]} -------------------------------------------------------------------------------- /BestPractices.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.29418.71 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BestPractices", "BestPractices\BestPractices.csproj", "{9A4269AF-7862-482C-A9FC-98D3542C4129}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{658E5A6F-7CF2-49A6-A6F7-2AC406DD6312}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {9A4269AF-7862-482C-A9FC-98D3542C4129}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {9A4269AF-7862-482C-A9FC-98D3542C4129}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {9A4269AF-7862-482C-A9FC-98D3542C4129}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {9A4269AF-7862-482C-A9FC-98D3542C4129}.Release|Any CPU.Build.0 = Release|Any CPU 20 | EndGlobalSection 21 | GlobalSection(SolutionProperties) = preSolution 22 | HideSolutionNode = FALSE 23 | EndGlobalSection 24 | GlobalSection(ExtensibilityGlobals) = postSolution 25 | SolutionGuid = {DBF77221-C9B0-4D57-9824-228B06CB58B5} 26 | EndGlobalSection 27 | EndGlobal 28 | -------------------------------------------------------------------------------- /BestPractices/AccessEvaluation.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Diagnostics; 3 | using System.Text.Json; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using System.Timers; 7 | using System; 8 | using System.Windows; 9 | 10 | namespace BestPractices 11 | { 12 | public partial class MainWindow : Window 13 | { 14 | private string ServicePrincipalID = string.Empty; 15 | 16 | private async Task AccessEvaluationTask() 17 | { 18 | string message = null; 19 | string[] scopes = new string[] { "user.read" }; 20 | Stopwatch sw = Stopwatch.StartNew(); 21 | List thisAppsAppRoles = null; 22 | 23 | try 24 | { 25 | string result; 26 | bool appRoleAssignmentRequired = false; 27 | 28 | // Has the ID Token expired? If so, reauthenticate the user 29 | // forceRefresh tells MSAL to get a new token. MSAL by default will cache the ID Token based on the Access Token's lifetime 30 | // Using an NBF claims challenge forces the broker to acquire a new ID Token 31 | if (usingOIDC && expiresAt <= DateTime.Now) 32 | { 33 | logger.Log($"ReAuth user. ID Token expired at {expiresAt}"); 34 | try 35 | { 36 | bool force = false; 37 | if (usingForce) 38 | { 39 | force = true; 40 | } 41 | await GetToken(TokenType.ID, new string[] { "" }, silent: true, forceRefresh: force); 42 | 43 | } 44 | catch (Exception ex) 45 | { 46 | userIsSignedIn = false; 47 | logger.Log(ex.Message); 48 | UpdateScreen($"User is not signed in. {ex.Message}"); 49 | return; 50 | } 51 | } 52 | 53 | // Doing access evaluation with Microsoft Graph is optional 54 | if (doAccessEvaluation == false) 55 | { 56 | UpdateScreen(); 57 | return; 58 | } 59 | 60 | logger.Log($"AccessEvaluation start"); 61 | 62 | // None of the values we need to do an access evaluation are avalible for users with Microsoft consumer accounts (outlook.com, hotmail.com, xbox.com, skype.com, .... 63 | if (tenantID != "9188040d-6c67-4c5b-b112-36a304b66dad") 64 | { 65 | // We need the current Service Principal for this app so that we can query the Service Principal for assigned roles 66 | // the format of the call to /servicePrincipals below /servicePrincipals(appId='{App.ClientId}') allows us to access a Service Principal in a different tenant 67 | // this is needed since this is a multi-tenant app 68 | if (ServicePrincipalID == string.Empty) 69 | { 70 | string SPsEndpoint = $"https://graph.microsoft.com/v1.0/servicePrincipals(appId='{App.ClientId}')?$select=id"; 71 | result = await AuthAndGetAPI(SPsEndpoint, scopes, silent: true); 72 | ServicePrincipalResults spResults = JsonSerializer.Deserialize(result); 73 | if (spResults != null) 74 | { 75 | ServicePrincipalID = spResults.id; 76 | } 77 | } 78 | 79 | // We are going to use Microsoft Graph to evaluate if the user should still have access to the app 80 | // Doing this check with Microsoft Graph, instead of using claims in the ID Token means the evaulation is up to the moment accurate 81 | // Claims in the ID Token could be up to 60 minutes out of date as MSAL will cache the token for it's lifetime 82 | // 83 | // For all the calls to Microsoft Graph we need, only user.read is required. 84 | // 85 | // Checks 86 | // From the user's profile (/me): 87 | // Has the user's account been disabled or deleted? 88 | // Has our ID Token been issued before the time for signInSessionsValidFromDateTime,refreshTokensValidFromDateTime? 89 | // 90 | // From the Service Principal for this app in this tenant 91 | // What are the approles for this app? Most of the time you will not need these but for this app, it lets us get the approle names 92 | // getting approles names in real time allow the demo to work for app roles defined as the app runs. 93 | // Is app assignment require for this app? 94 | // Is the app disabled to sign in users? 95 | // 96 | // From the user's app roles assignments for this Service Principal (this app) 97 | // If the Service Principal requires assignment and there no assigned roles, consider the user signed out. 98 | // Gather, and display, the user's role assignments to this app. 99 | // 100 | // From the user's member objects 101 | // Get the list of Azure AD roles and groups for which the user is a member 102 | // which are on our list of Azure AD roles and groups for which we want to know if the user is a member 103 | // If the user is assigned the Group Administrator role, 104 | 105 | StringBuilder batch = new StringBuilder(); 106 | batch.Append($"{{\"requests\":["); 107 | batch.Append($"{{\"id\":\"1\",\"method\":\"GET\",\"url\":\"/me?$select=signInSessionsValidFromDateTime,refreshTokensValidFromDateTime,deletedDateTime,accountEnabled\"}},"); 108 | batch.Append($"{{\"id\":\"2\",\"dependsOn\": [ \"1\" ],\"method\":\"GET\",\"url\":\"/servicePrincipals(appId='{App.ClientId}')?$select=appRoles,appRoleAssignmentRequired,accountEnabled\"}},"); 109 | batch.Append($"{{\"id\":\"3\",\"dependsOn\": [ \"2\" ],\"method\":\"GET\",\"url\":\"/me/appRoleAssignments?$filter=resourceId eq {ServicePrincipalID}\"}}"); 110 | 111 | batch.Append($",{{\"id\":\"4\",\"dependsOn\": [ \"3\" ],\"method\": \"POST\",\"url\":\"me/checkMemberObjects\",\"body\":{{\"ids\":["); 112 | string delimeter = string.Empty; 113 | foreach (RoleAndGroupMemberInfo roleOrGroup in rolesAndGroupsData.roleAndGroupMembership) 114 | { 115 | string groupstr = $"{delimeter}\"{roleOrGroup.ID}\""; 116 | batch.Append(groupstr); 117 | delimeter = ","; 118 | } 119 | batch.Append($"]}},\"headers\":{{\"Content-Type\":\"application/json\"}}}}"); 120 | 121 | batch.Append($"]}}"); 122 | string batchBody = batch.ToString(); 123 | 124 | result = await AuthAndPostAPI("https://graph.microsoft.com/v1.0/$batch", scopes, batchBody, silent: true); 125 | if (result != null) 126 | { 127 | BatchResult batchResult = JsonSerializer.Deserialize(result); 128 | foreach (Response r in batchResult.responses) 129 | { 130 | string bodyJSON = r.body.ToString(); 131 | switch (r.id) 132 | { 133 | case "1": 134 | UserAccessEvaulationResults uaeResults = JsonSerializer.Deserialize(bodyJSON); 135 | if (uaeResults != null) 136 | { 137 | if (uaeResults.accountEnabled == false) 138 | { 139 | userIsSignedIn = false; 140 | message = "User account disabled. User considered signed out."; 141 | logger.Log(message); 142 | UpdateScreen(message); 143 | return; 144 | } 145 | if (uaeResults.deletedDateTime != null) 146 | { 147 | userIsSignedIn = false; 148 | message = "User account deleted. User considered signed out."; 149 | logger.Log(message); 150 | UpdateScreen(message); 151 | return; 152 | } 153 | if (DateTime.Compare(issuedAt, uaeResults.signInSessionsValidFromDateTime.ToLocalTime()) < 0 154 | || DateTime.Compare(issuedAt, uaeResults.refreshTokensValidFromDateTime.ToLocalTime()) < 0) 155 | { 156 | userIsSignedIn = false; 157 | message = $"ID Token issed at {issuedAt}. User sessions have been revoked at {uaeResults.refreshTokensValidFromDateTime.ToLocalTime()}. User considered signed out."; 158 | logger.Log(message); 159 | UpdateScreen(message); 160 | return; 161 | } 162 | } 163 | break; 164 | 165 | case "2": 166 | ServicePrincipalResults spResults = JsonSerializer.Deserialize(bodyJSON); 167 | if (spResults != null) 168 | { 169 | if (spResults.accountEnabled == false) 170 | { 171 | // ServicePrincipal is disabled for authentication. Consider the user signed out 172 | userIsSignedIn = false; 173 | message = $"Enterprise App has been disabled for user authentication. User is considered signed out."; 174 | logger.Log(message); 175 | UpdateScreen(message); 176 | return; 177 | } 178 | 179 | if (spResults.appRoles != null) 180 | { 181 | thisAppsAppRoles = spResults.appRoles; 182 | } 183 | else 184 | { 185 | thisAppsAppRoles = null; 186 | } 187 | 188 | appRoleAssignmentRequired = spResults.appRoleAssignmentRequired; 189 | } 190 | break; 191 | 192 | case "3": 193 | sbRoles.Clear(); 194 | RoleResults roleResults = JsonSerializer.Deserialize(bodyJSON); 195 | if (roleResults.value.Count == 0 && appRoleAssignmentRequired == true) 196 | { 197 | // User must be assigned to the app and this user is not assigned (There are no role assignments for this user) 198 | // The user must have signed into the app before the app required assignment. 199 | // Sign out the user. 200 | userIsSignedIn = false; 201 | message = $"User assignment required and the user is not assigned. User is considered signed out."; 202 | logger.Log(message); 203 | UpdateScreen(message); 204 | return; 205 | } 206 | else 207 | { 208 | bool found = false; 209 | foreach (Role role in roleResults.value) 210 | { 211 | // the app zeros and dashes Role ID means the user is assigned and has the default role. 212 | if (role.appRoleId == "00000000-0000-0000-0000-000000000000") 213 | { 214 | sbRoles.AppendLine($"Default Access "); 215 | } 216 | else 217 | { 218 | if (thisAppsAppRoles != null) 219 | { 220 | foreach (AppRole appRole in thisAppsAppRoles) 221 | { 222 | if (appRole.id == role.appRoleId) 223 | { 224 | sbRoles.AppendLine($"{appRole.displayName} "); 225 | found = true; 226 | break; 227 | } 228 | } 229 | } 230 | if (!found) 231 | { 232 | sbRoles.AppendLine($"Unknown:{role.appRoleId} "); 233 | } 234 | } 235 | } 236 | } 237 | break; 238 | 239 | case "4": 240 | groupAdmin = false; 241 | foreach (RoleAndGroupMemberInfo roleOrGroup in rolesAndGroupsData.roleAndGroupMembership) 242 | { 243 | roleOrGroup.IsMember = "No"; 244 | } 245 | 246 | GroupResults groupResults = JsonSerializer.Deserialize(bodyJSON); 247 | if (groupResults != null) 248 | { 249 | foreach (string groupID in groupResults.value) 250 | { 251 | foreach (RoleAndGroupMemberInfo roleOrGroup in rolesAndGroupsData.roleAndGroupMembership) 252 | { 253 | if (roleOrGroup.ID == groupID) 254 | { 255 | roleOrGroup.IsMember = "Yes"; 256 | } 257 | } 258 | if (groupID == "fdd7a751-b60b-444a-984c-02652fe8fa1c") 259 | { 260 | groupAdmin = true; 261 | } 262 | } 263 | } 264 | break; 265 | } 266 | } 267 | } 268 | } 269 | else 270 | { 271 | logger.Log("No evaluation possible for Microsoft consumer accounts"); 272 | } 273 | } 274 | catch (Exception ex) 275 | { 276 | if (ex.InnerException != null && ex.InnerException.Message != null && ex.InnerException.Message == "CAEEvent") 277 | { 278 | userIsSignedIn = false; 279 | message = "Continous Access Evaluation Event was received. Must sign in again."; 280 | } 281 | else 282 | { 283 | message = $"AccessEvaluation failed with: {ex.Message}"; 284 | logger.Log(message); 285 | } 286 | } 287 | 288 | logger.Log($"Access Evaluation took {sw.ElapsedMilliseconds} ms"); 289 | UpdateScreen(message); 290 | 291 | } 292 | 293 | private async void AccessEvaluationFunction(Object source, ElapsedEventArgs e) 294 | { 295 | await AccessEvaluationTask(); 296 | } 297 | } 298 | } 299 | -------------------------------------------------------------------------------- /BestPractices/Account.contrast-white.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kylemar/BestPracticesDemo/902e2ae375143fbf37888b5a91065c0a30076ddc/BestPractices/Account.contrast-white.ico -------------------------------------------------------------------------------- /BestPractices/App.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /BestPractices/App.xaml: -------------------------------------------------------------------------------- 1 |  6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /BestPractices/App.xaml.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Identity.Client; 2 | using System.Windows; 3 | 4 | namespace BestPractices 5 | { 6 | /// 7 | /// Interaction logic for App.xaml 8 | /// 9 | public partial class App : Application 10 | { 11 | static App() 12 | { 13 | } 14 | 15 | // Below are the clientId (Application Id) of your app registration and the tenant information. 16 | // You have to replace: 17 | // - the content of ClientID with the Application Id for your app registration 18 | public static string ClientId = "182a4f96-9d7f-4fc7-a387-dd68c15e52d2"; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /BestPractices/AppResults.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace BestPractices 8 | { 9 | internal class AppResults 10 | { 11 | public string odatacontext { get; set; } 12 | public List value { get; set; } 13 | } 14 | 15 | public class Value 16 | { 17 | public List appRoles { get; set; } 18 | } 19 | 20 | 21 | } 22 | -------------------------------------------------------------------------------- /BestPractices/AppRole.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace BestPractices 8 | { 9 | public class AppRole 10 | { 11 | public List allowedMemberTypes { get; set; } 12 | public string description { get; set; } 13 | public string displayName { get; set; } 14 | public string id { get; set; } 15 | public bool isEnabled { get; set; } 16 | public string origin { get; set; } 17 | public string value { get; set; } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /BestPractices/BatchResult.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using static System.Windows.Forms.VisualStyles.VisualStyleElement.Tab; 7 | 8 | namespace BestPractices 9 | { 10 | public class Response 11 | { 12 | public string id { get; set; } 13 | public int status { get; set; } 14 | public object body { get; set; } 15 | } 16 | 17 | internal class BatchResult 18 | { 19 | public List responses { get; set; } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /BestPractices/BestPractices.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {9A4269AF-7862-482C-A9FC-98D3542C4129} 8 | WinExe 9 | BestPractices 10 | BestPractices 11 | v4.8 12 | 512 13 | {60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} 14 | 4 15 | true 16 | 17 | 18 | 19 | AnyCPU 20 | true 21 | full 22 | false 23 | bin\Debug\ 24 | DEBUG;TRACE 25 | prompt 26 | 4 27 | 28 | 29 | AnyCPU 30 | pdbonly 31 | true 32 | bin\Release\ 33 | TRACE 34 | prompt 35 | 4 36 | 37 | 38 | Account.contrast-white.ico 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 4.0 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | MSBuild:Compile 63 | Designer 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | MSBuild:Compile 81 | Designer 82 | 83 | 84 | App.xaml 85 | Code 86 | 87 | 88 | MainWindow.xaml 89 | Code 90 | 91 | 92 | 93 | 94 | Code 95 | 96 | 97 | True 98 | True 99 | Resources.resx 100 | 101 | 102 | True 103 | Settings.settings 104 | True 105 | 106 | 107 | ResXFileCodeGenerator 108 | Resources.Designer.cs 109 | 110 | 111 | SettingsSingleFileGenerator 112 | Settings.Designer.cs 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 4.71.1 121 | 122 | 123 | 4.71.1 124 | 125 | 126 | 9.0.4 127 | 128 | 129 | 130 | 131 | 132 | 133 | -------------------------------------------------------------------------------- /BestPractices/CallRestAPIs.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics; 4 | using System.Linq; 5 | using System.Net.Http.Headers; 6 | using System.Net.Http; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | using System.Windows; 10 | using Microsoft.Identity.Client; 11 | 12 | namespace BestPractices 13 | { 14 | public partial class MainWindow : Window 15 | { 16 | private async Task AuthAndPostAPI(string APIEndpoint, string[] scopes, string body, bool silent = false, bool forceRefresh = false) 17 | { 18 | sbResponse.Clear(); 19 | string results = null; 20 | string message = "AuthAndPostAPI ["; 21 | foreach (string s in scopes) 22 | { 23 | message += $"{s} "; 24 | } 25 | message += $"] {APIEndpoint}"; 26 | logger.Log(message); 27 | 28 | var accessToken = await GetToken(TokenType.Access, scopes, null, silent, forceRefresh); 29 | if (null != accessToken) 30 | { 31 | if (!string.IsNullOrEmpty(APIEndpoint)) 32 | { 33 | try 34 | { 35 | results = await PostHttpContentWithToken(APIEndpoint, accessToken, scopes, body, handleCAE: !silent); 36 | } 37 | catch (Exception ex) 38 | { 39 | throw (ex); 40 | } 41 | } 42 | } 43 | return results; 44 | } 45 | 46 | private async Task AuthAndGetAPI(string APIEndpoint, string[] scopes, bool silent = false, bool forceRefresh = false) 47 | { 48 | sbResponse.Clear(); 49 | string results = null; 50 | string message = "AuthAndGetAPI ["; 51 | foreach (string s in scopes) 52 | { 53 | message += $"{s} "; 54 | } 55 | message += $"] {APIEndpoint}"; 56 | logger.Log(message); 57 | 58 | var accessToken = await GetToken(TokenType.Access, scopes, null, silent, forceRefresh); 59 | if (null != accessToken) 60 | { 61 | if (!string.IsNullOrEmpty(APIEndpoint)) 62 | { 63 | try 64 | { 65 | results = await GetHttpContentWithToken(APIEndpoint, accessToken, scopes, !silent); 66 | } 67 | catch (Exception ex) 68 | { 69 | throw (ex); 70 | } 71 | } 72 | } 73 | return results; 74 | } 75 | 76 | /// 77 | /// Perform an HTTP GET request to a URL using an HTTP Authorization header 78 | /// 79 | /// The URL 80 | /// The token 81 | /// String containing the results of the GET operation 82 | public async Task GetHttpContentWithToken(string url, string token, string[] scopes, bool handleCAE = true) 83 | { 84 | return await HttpContentWithToken(HttpMethod.Get, url, token, scopes, handleCAE, null); 85 | } 86 | 87 | public async Task PostHttpContentWithToken(string url, string token, string[] scopes, string body, bool handleCAE = true) 88 | { 89 | return await HttpContentWithToken(HttpMethod.Post, url, token, scopes, handleCAE, body); 90 | } 91 | 92 | static readonly HttpClient httpClient = new HttpClient(); 93 | 94 | public async Task HttpContentWithToken(HttpMethod method, string url, string token, string[] scopes, bool handleCAE, string body) 95 | { 96 | Stopwatch sw = Stopwatch.StartNew(); 97 | Exception innerEx = null; 98 | string message; 99 | 100 | //Add the token in Authorization header 101 | httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); 102 | 103 | HttpResponseMessage APIresponse; 104 | try 105 | { 106 | if (method == HttpMethod.Post) 107 | { 108 | var content = new StringContent(body, Encoding.UTF8, "application/json"); 109 | APIresponse = await httpClient.PostAsync(url, content); 110 | } 111 | else if (method == HttpMethod.Get) 112 | { 113 | HttpRequestMessage APIrequest = new HttpRequestMessage(method, url); 114 | APIresponse = await httpClient.SendAsync(APIrequest); 115 | } 116 | else 117 | { 118 | return null; 119 | } 120 | 121 | if (APIresponse.IsSuccessStatusCode) 122 | { 123 | string content = await APIresponse.Content.ReadAsStringAsync(); 124 | logger.Log($"Successful Graph call took {sw.ElapsedMilliseconds} ms"); 125 | return content; 126 | } 127 | else 128 | { 129 | string claimChallenge = WwwAuthenticateParameters.GetClaimChallengeFromResponseHeaders(APIresponse.Headers); 130 | if (APIresponse.StatusCode == System.Net.HttpStatusCode.Unauthorized && claimChallenge != null) 131 | { 132 | logger.Log($"CAE Claims challenge received: {claimChallenge}"); 133 | UpdateScreen(); 134 | 135 | if (handleCAE) 136 | { 137 | var newAccessToken = await GetToken(TokenType.Access, scopes, claimChallenge); 138 | if (null != newAccessToken) 139 | { 140 | var APIrequestAfterCAE = new HttpRequestMessage(HttpMethod.Get, url); 141 | APIrequestAfterCAE.Headers.Authorization = 142 | new AuthenticationHeaderValue("Bearer", newAccessToken); 143 | 144 | HttpResponseMessage APIresponseAfterCAE; 145 | APIresponseAfterCAE = await httpClient.SendAsync( 146 | APIrequestAfterCAE); 147 | 148 | if (APIresponseAfterCAE.IsSuccessStatusCode) 149 | { 150 | var content = await APIresponseAfterCAE.Content.ReadAsStringAsync(); 151 | var expandedContent = content.Replace(",", "," + Environment.NewLine); 152 | return expandedContent; 153 | } 154 | } 155 | } 156 | else 157 | { 158 | throw new Exception("CAEEvent"); 159 | } 160 | 161 | } 162 | 163 | message = $"Status:{APIresponse.StatusCode} Reason:{APIresponse.ReasonPhrase} "; 164 | string messageToLog = $"Call to {url} failed with {message}"; 165 | foreach (KeyValuePair> header in APIresponse.Headers) 166 | { 167 | foreach (string value in header.Value) 168 | { 169 | messageToLog += $" | {header.Key}: {value}"; 170 | } 171 | } 172 | logger.Log(messageToLog); 173 | } 174 | } 175 | catch (Exception ex) 176 | { 177 | message = ex.Message; 178 | innerEx = ex; 179 | } 180 | throw new Exception($"Call to {url} failed with {message}", innerEx); 181 | } 182 | 183 | } 184 | } 185 | -------------------------------------------------------------------------------- /BestPractices/GroupResults.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Text.Json; 3 | 4 | namespace BestPractices 5 | { 6 | public class GroupResults 7 | { 8 | public string odatacontext { get; set; } 9 | public List value { get; set; } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /BestPractices/Logger.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace BestPractices 9 | { 10 | internal enum LogType 11 | { 12 | All, 13 | Screen, 14 | Console, 15 | File 16 | } 17 | /// 18 | /// Possibility the worlds most simple logger 19 | /// 20 | internal class Logger 21 | { 22 | string fileName; 23 | readonly StringBuilder sblog; 24 | 25 | public Logger(StringBuilder sbLog) 26 | { 27 | sblog = sbLog; 28 | } 29 | 30 | public void Start() 31 | { 32 | fileName = $"{DateTime.Now:yyyy-MM-dd-HH-mm-ss}.log"; 33 | } 34 | 35 | public void Log(string message, LogType logType = LogType.All ) 36 | { 37 | string messageToShow; 38 | 39 | messageToShow = $"{DateTime.Now}-{message}"; 40 | 41 | if (logType == LogType.All || logType == LogType.Console) 42 | { 43 | Console.WriteLine(messageToShow); 44 | } 45 | 46 | if (logType == LogType.All || logType == LogType.Screen) 47 | { 48 | if (sblog.Length > 65536) 49 | { 50 | sblog.Clear(); 51 | } 52 | sblog.AppendLine(messageToShow); 53 | } 54 | 55 | if (logType == LogType.All || logType == LogType.File) 56 | { 57 | try 58 | { 59 | File.AppendAllText(fileName, $"{messageToShow}\n"); 60 | } 61 | catch { } 62 | } 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /BestPractices/MainWindow.xaml: -------------------------------------------------------------------------------- 1 |  14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 55 | 56 | 57 | 58 | 60 | 61 | 62 | 63 | 73 | 74 | 75 | 76 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 |