Skip to content

Commit 2ff32cd

Browse files
author
Kalyan Krishna
committed
Updated post code review
1 parent f158355 commit 2ff32cd

12 files changed

+94
-258
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -132,3 +132,4 @@ packages
132132
/4-WebApp-your-API/4-2-B2C/TodoListService/obj
133133
/4-WebApp-your-API/4-2-B2C/Client/bin
134134
/4-WebApp-your-API/4-2-B2C/TodoListService/bin
135+
/2-WebApp-graph-user/2-1-Call-MSGraph/.vscode

2-WebApp-graph-user/2-1-Call-MSGraph/AspnetCoreWebApp-calls-Microsoft-Graph.sln

+1-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00
33
# Visual Studio Version 16
44
VisualStudioVersion = 16.0.30413.136
55
MinimumVisualStudioVersion = 10.0.40219.1
6-
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WebApp-OpenIDConnect-DotNet", "WebApp-OpenIDConnect-DotNet.csproj", "{76F9C1E5-3CF7-4C9A-A0EC-D15B5F11022D}"
6+
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WebApp-OpenIDConnect-DotNet-graph", "WebApp-OpenIDConnect-DotNet-graph.csproj", "{76F9C1E5-3CF7-4C9A-A0EC-D15B5F11022D}"
77
EndProject
88
Global
99
GlobalSection(SolutionConfigurationPlatforms) = preSolution

2-WebApp-graph-user/2-1-Call-MSGraph/Controllers/HomeController.cs

+21-38
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1-
using _2_1_Call_MSGraph.Models;
1+
using CallMSGraph.Models;
22
using Microsoft.AspNetCore.Authorization;
33
using Microsoft.AspNetCore.Mvc;
4+
using Microsoft.Extensions.Configuration;
45
using Microsoft.Extensions.Logging;
56
using Microsoft.Graph;
67
using Microsoft.Identity.Web;
@@ -9,7 +10,7 @@
910
using System.IO;
1011
using System.Threading.Tasks;
1112

12-
namespace _2_1_Call_MSGraph.Controllers
13+
namespace CallMSGraph.Controllers
1314
{
1415
[Authorize]
1516
public class HomeController : Controller
@@ -20,13 +21,18 @@ public class HomeController : Controller
2021

2122
private readonly MicrosoftIdentityConsentAndConditionalAccessHandler _consentHandler;
2223

24+
private string[] _graphScopes = new[] { "user.read" };
25+
2326
public HomeController(ILogger<HomeController> logger,
24-
GraphServiceClient graphServiceClient,
25-
MicrosoftIdentityConsentAndConditionalAccessHandler consentHandler)
27+
IConfiguration configuration,
28+
GraphServiceClient graphServiceClient,
29+
MicrosoftIdentityConsentAndConditionalAccessHandler consentHandler)
2630
{
2731
_logger = logger;
2832
_graphServiceClient = graphServiceClient;
2933
this._consentHandler = consentHandler;
34+
35+
_graphScopes = configuration.GetValue<string>("DownstreamApi:Scopes")?.Split(' ');
3036
}
3137

3238
[AuthorizeForScopes(ScopeKeySection = "DownstreamApi:Scopes")]
@@ -40,52 +46,30 @@ public IActionResult Index()
4046
[AuthorizeForScopes(ScopeKeySection = "DownstreamApi:Scopes")]
4147
public async Task<IActionResult> Profile()
4248
{
43-
Microsoft.Graph.User currentUser = null;
49+
User currentUser = null;
4450

4551
try
4652
{
4753
currentUser = await _graphServiceClient.Me.Request().GetAsync();
4854
}
49-
catch (System.Exception ex)
55+
catch (System.Exception ex) // Catch CAE exception from Graph SDK
5056
{
51-
if (ex is WebApiMsalUiRequiredException || (ex is ServiceException && ex.Message.Trim().Contains("Continuous access evaluation resulted in claims challenge")))
57+
if (ex is ServiceException && ex.Message.Trim().Contains("Continuous access evaluation resulted in claims challenge"))
5258
{
53-
if (ex is WebApiMsalUiRequiredException)
59+
try
5460
{
55-
try
56-
{
57-
WebApiMsalUiRequiredException hex = ex as WebApiMsalUiRequiredException;
58-
Console.WriteLine($"{hex}");
59-
60-
var claimChallenge = AuthenticationHeaderHelper.ExtractHeaderValues(hex);
61-
_consentHandler.ChallengeUser(new string[] { "user.read" }, claimChallenge);
62-
63-
return new EmptyResult();
64-
}
65-
catch (Exception ex2)
66-
{
67-
_consentHandler.HandleException(ex2);
68-
}
61+
ServiceException svcex = ex as ServiceException;
62+
Console.WriteLine($"{svcex}");
63+
var claimChallenge = AuthenticationHeaderHelper.ExtractClaimChallengeFromHttpHeader(svcex.ResponseHeaders);
64+
_consentHandler.ChallengeUser(_graphScopes, claimChallenge);
65+
return new EmptyResult();
6966
}
70-
71-
if (ex is ServiceException)
67+
catch (Exception ex2)
7268
{
73-
try
74-
{
75-
ServiceException svcex = ex as ServiceException;
76-
Console.WriteLine($"{svcex}");
77-
var claimChallenge = AuthenticationHeaderHelper.ExtractHeaderValues(svcex.ResponseHeaders);
78-
_consentHandler.ChallengeUser(new string[] { "user.read" }, claimChallenge);
79-
return new EmptyResult();
80-
}
81-
catch (Exception ex2)
82-
{
83-
_consentHandler.HandleException(ex2);
84-
}
69+
_consentHandler.HandleException(ex2);
8570
}
8671
}
8772

88-
8973
try
9074
{
9175
// Get user photo
@@ -100,7 +84,6 @@ public async Task<IActionResult> Profile()
10084
Console.WriteLine($"{pex}");
10185
ViewData["Photo"] = null;
10286
}
103-
10487
}
10588
ViewData["Me"] = currentUser;
10689
return View();

2-WebApp-graph-user/2-1-Call-MSGraph/Models/AuthenticationHeaderHelper.cs

+4-34
Original file line numberDiff line numberDiff line change
@@ -4,46 +4,16 @@
44
using System.Threading.Tasks;
55
using System.Net.Http.Headers;
66

7-
namespace _2_1_Call_MSGraph.Models
7+
namespace CallMSGraph.Models
88
{
99
public class AuthenticationHeaderHelper
1010
{
1111
/// <summary>
12-
/// Extract claims from WwwAuthenticate header and returns the value.
12+
/// Extracts the claim challenge from HTTP header.
1313
/// </summary>
14-
/// <param name="response"></param>
14+
/// <param name="httpResponseHeaders">The HTTP response headers.</param>
1515
/// <returns></returns>
16-
internal static string ExtractHeaderValues(WebApiMsalUiRequiredException response)
17-
{
18-
if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized && response.Headers.WwwAuthenticate.Any())
19-
{
20-
AuthenticationHeaderValue bearer = response.Headers.WwwAuthenticate.First(v => v.Scheme == "Bearer");
21-
IEnumerable<string> parameters = bearer.Parameter.Split(',').Select(v => v.Trim()).ToList();
22-
var errorValue = GetParameterValue(parameters, "error");
23-
24-
try
25-
{
26-
// read the header and checks if it conatins error with insufficient_claims value.
27-
if (null != errorValue && "insufficient_claims" == errorValue)
28-
{
29-
var claimChallengeParameter = GetParameterValue(parameters, "claims");
30-
if (null != claimChallengeParameter)
31-
{
32-
var claimChallenge = ConvertBase64String(claimChallengeParameter);
33-
34-
return claimChallenge;
35-
}
36-
}
37-
}
38-
catch (Exception ex)
39-
{
40-
throw ex;
41-
}
42-
}
43-
return null;
44-
}
45-
46-
internal static string ExtractHeaderValues(HttpResponseHeaders httpResponseHeaders)
16+
internal static string ExtractClaimChallengeFromHttpHeader(HttpResponseHeaders httpResponseHeaders)
4717
{
4818
if (httpResponseHeaders.WwwAuthenticate.Any())
4919
{

2-WebApp-graph-user/2-1-Call-MSGraph/Models/ErrorViewModel.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
namespace _2_1_Call_MSGraph.Models
1+
namespace CallMSGraph.Models
22
{
33
public class ErrorViewModel
44
{

2-WebApp-graph-user/2-1-Call-MSGraph/Models/WebApiMsalUiRequiredException.cs

-37
This file was deleted.

2-WebApp-graph-user/2-1-Call-MSGraph/Program.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
using Microsoft.AspNetCore.Hosting;
22
using Microsoft.Extensions.Hosting;
33

4-
namespace _2_1_Call_MSGraph
4+
namespace CallMSGraph
55
{
66
public class Program
77
{

0 commit comments

Comments
 (0)