Skip to content

Commit 407932f

Browse files
authored
Jmprieur/fix with graph service (#87)
* Improving the MsalUiRequiredExceptionFilterAttribute so that it accepts MsalUiRequiredExceptions as inner exceptions. Refactoring of the HomeController to extract the creation of the GraphServiceClient, and moving the acquisition of the token in authentication provider callback * Renaming
1 parent 3bdc589 commit 407932f

File tree

4 files changed

+49
-28
lines changed

4 files changed

+49
-28
lines changed

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

Lines changed: 20 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
using Microsoft.AspNetCore.Authorization;
66
using Microsoft.AspNetCore.Mvc;
77
using Microsoft.Extensions.Options;
8+
using Graph=Microsoft.Graph;
89
using Microsoft.Identity.Web.Client;
910
using WebApp_OpenIDConnect_DotNet.Infrastructure;
1011
using WebApp_OpenIDConnect_DotNet.Models;
@@ -15,13 +16,13 @@ namespace WebApp_OpenIDConnect_DotNet.Controllers
1516
[Authorize]
1617
public class HomeController : Controller
1718
{
18-
readonly ITokenAcquisition tokenAcquisition;
19-
readonly WebOptions webOptions;
19+
readonly ITokenAcquisition tokenAcquisition;
20+
readonly WebOptions webOptions;
2021

21-
public HomeController(ITokenAcquisition tokenAcquisition,
22+
public HomeController(ITokenAcquisition tokenAcquisition,
2223
IOptions<WebOptions> webOptionValue)
2324
{
24-
this.tokenAcquisition = tokenAcquisition;
25+
this.tokenAcquisition = tokenAcquisition;
2526
this.webOptions = webOptionValue.Value;
2627
}
2728

@@ -30,18 +31,12 @@ public IActionResult Index()
3031
return View();
3132
}
3233

33-
[MsalUiRequiredExceptionFilter(Scopes = new[] {Constants.ScopeUserRead})]
34+
[MsalUiRequiredExceptionFilter(Scopes = new[] { Constants.ScopeUserRead })]
3435
public async Task<IActionResult> Profile()
3536
{
36-
// Initialize the GraphServiceClient.
37-
var graphClient = await GraphServiceClientFactory.GetAuthenticatedGraphClient(async () =>
38-
{
39-
string result = await tokenAcquisition.GetAccessTokenOnBehalfOfUser(
40-
HttpContext, new[] { Constants.ScopeUserRead });
41-
return result;
42-
}, webOptions.GraphApiUrl);
37+
// Initialize the GraphServiceClient.
38+
Graph::GraphServiceClient graphClient = GetGraphServiceClient(new[] { Constants.ScopeUserRead });
4339

44-
// Get user profile info.
4540
var me = await graphClient.Me.Request().GetAsync();
4641
ViewData["Me"] = me;
4742

@@ -55,16 +50,26 @@ public async Task<IActionResult> Profile()
5550
catch (System.Exception)
5651
{
5752
ViewData["Photo"] = null;
58-
}
53+
}
5954

6055
return View();
6156
}
6257

58+
private Graph::GraphServiceClient GetGraphServiceClient(string[] scopes)
59+
{
60+
return GraphServiceClientFactory.GetAuthenticatedGraphClient(async () =>
61+
{
62+
string result = await tokenAcquisition.GetAccessTokenOnBehalfOfUser(
63+
HttpContext, scopes);
64+
return result;
65+
}, webOptions.GraphApiUrl);
66+
}
67+
6368
[AllowAnonymous]
6469
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
6570
public IActionResult Error()
6671
{
67-
return View(new ErrorViewModel {RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier});
72+
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
6873
}
6974
}
7075
}
Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,37 @@
11
using Microsoft.Graph;
22
using System;
3-
using System.Collections.Generic;
4-
using System.Linq;
3+
using System.Net.Http;
54
using System.Net.Http.Headers;
65
using System.Threading.Tasks;
76

87
namespace WebApp_OpenIDConnect_DotNet.Services
98
{
109
public class GraphServiceClientFactory
1110
{
12-
public static async Task<GraphServiceClient> GetAuthenticatedGraphClient(Func<Task<string>> acquireAccessToken,
11+
public static GraphServiceClient GetAuthenticatedGraphClient(Func<Task<string>> acquireAccessToken,
1312
string baseUrl = null)
1413
{
15-
// Fetch the access token
14+
15+
return new GraphServiceClient(baseUrl, new CustomAuthenticationProvider(acquireAccessToken));
16+
}
17+
}
18+
19+
class CustomAuthenticationProvider : IAuthenticationProvider
20+
{
21+
public CustomAuthenticationProvider(Func<Task<string>> acquireTokenCallback)
22+
{
23+
acquireAccessToken = acquireTokenCallback;
24+
}
25+
26+
private Func<Task<string>> acquireAccessToken;
27+
28+
public async Task AuthenticateRequestAsync(HttpRequestMessage request)
29+
{
1630
string accessToken = await acquireAccessToken.Invoke();
1731

18-
return new GraphServiceClient(baseUrl, new DelegateAuthenticationProvider(
19-
async (requestMessage) =>
20-
{
21-
// Append the access token to the request.
22-
requestMessage.Headers.Authorization = new AuthenticationHeaderValue(
23-
Infrastructure.Constants.BearerAuthorizationScheme, accessToken);
24-
}));
32+
// Append the access token to the request.
33+
request.Headers.Authorization = new AuthenticationHeaderValue(
34+
Infrastructure.Constants.BearerAuthorizationScheme, accessToken);
2535
}
2636
}
2737
}

2-WebApp-graph-user/2-1-Call-MSGraph/appsettings.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,5 +17,5 @@
1717
}
1818
},
1919
"AllowedHosts": "*",
20-
"GraphApiUrl": "https://graph.microsoft.com/v1.0"
20+
"GraphApiUrl": "https://graph.microsoft.com/beta"
2121
}

Microsoft.Identity.Web/Client/MsalUiRequiredExceptionFilterAttribute.cs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,13 @@ public class MsalUiRequiredExceptionFilterAttribute : ExceptionFilterAttribute
2727

2828
public override void OnException(ExceptionContext context)
2929
{
30-
if (context.Exception is MsalUiRequiredException msalUiRequiredException)
30+
MsalUiRequiredException msalUiRequiredException = context.Exception as MsalUiRequiredException;
31+
if (msalUiRequiredException == null)
32+
{
33+
msalUiRequiredException = context.Exception?.InnerException as MsalUiRequiredException;
34+
}
35+
36+
if (msalUiRequiredException!=null)
3137
{
3238
if (CanBeSolvedByReSignInUser(msalUiRequiredException))
3339
{

0 commit comments

Comments
 (0)