Skip to content

Commit 3bdc589

Browse files
irvinesundayjmprieur
authored andcommitted
Update to Microsoft.Graph SDK (#86)
* Adding Microsoft.Graph lib. and factory class for creating authenticated Graph clients * Using SDK to retrieve user info. and photo * Code fix to display Generic type property values for user info. * Code fix for fetching user photo from Graph. * Removing redundant code * Re-adding the Graph Service back to the project * Updating README to include updated GraphApiUrl
1 parent 7049166 commit 3bdc589

File tree

12 files changed

+95
-110
lines changed

12 files changed

+95
-110
lines changed

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

Lines changed: 29 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,28 @@
1-
using System.Diagnostics;
1+
using System;
2+
using System.Diagnostics;
3+
using System.IO;
24
using System.Threading.Tasks;
35
using Microsoft.AspNetCore.Authorization;
46
using Microsoft.AspNetCore.Mvc;
7+
using Microsoft.Extensions.Options;
58
using Microsoft.Identity.Web.Client;
69
using WebApp_OpenIDConnect_DotNet.Infrastructure;
710
using WebApp_OpenIDConnect_DotNet.Models;
8-
using WebApp_OpenIDConnect_DotNet.Services.GraphOperations;
11+
using WebApp_OpenIDConnect_DotNet.Services;
912

1013
namespace WebApp_OpenIDConnect_DotNet.Controllers
1114
{
1215
[Authorize]
1316
public class HomeController : Controller
1417
{
1518
readonly ITokenAcquisition tokenAcquisition;
16-
private readonly IGraphApiOperations graphApiOperations;
19+
readonly WebOptions webOptions;
1720

1821
public HomeController(ITokenAcquisition tokenAcquisition,
19-
IGraphApiOperations graphApiOperations)
22+
IOptions<WebOptions> webOptionValue)
2023
{
2124
this.tokenAcquisition = tokenAcquisition;
22-
this.graphApiOperations = graphApiOperations;
25+
this.webOptions = webOptionValue.Value;
2326
}
2427

2528
public IActionResult Index()
@@ -30,14 +33,29 @@ public IActionResult Index()
3033
[MsalUiRequiredExceptionFilter(Scopes = new[] {Constants.ScopeUserRead})]
3134
public async Task<IActionResult> Profile()
3235
{
33-
var accessToken =
34-
await tokenAcquisition.GetAccessTokenOnBehalfOfUser(HttpContext, new[] {Constants.ScopeUserRead});
35-
36-
var me = await graphApiOperations.GetUserInformation(accessToken);
37-
var photo = await graphApiOperations.GetPhotoAsBase64Async(accessToken);
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);
3843

44+
// Get user profile info.
45+
var me = await graphClient.Me.Request().GetAsync();
3946
ViewData["Me"] = me;
40-
ViewData["Photo"] = photo;
47+
48+
try
49+
{
50+
// Get user photo
51+
var photoStream = await graphClient.Me.Photo.Content.Request().GetAsync();
52+
byte[] photoByte = ((MemoryStream)photoStream).ToArray();
53+
ViewData["Photo"] = Convert.ToBase64String(photoByte);
54+
}
55+
catch (System.Exception)
56+
{
57+
ViewData["Photo"] = null;
58+
}
4159

4260
return View();
4361
}

2-WebApp-graph-user/2-1-Call-MSGraph/README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ Go to the `"2-WebApp-graph-user\2-1-Call-MSGraph"` folder
6565
- In case you want to deploy your app in Sovereign or national clouds, ensure the `GraphApiUrl` option matches the one you want. By default this is Microsoft Graph in the Azure public cloud
6666

6767
```JSon
68-
"GraphApiUrl": "https://graph.microsoft.com"
68+
"GraphApiUrl": "https://graph.microsoft.com/v1.0"
6969
```
7070

7171
### Step 3: Run the sample
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
using Microsoft.Extensions.Configuration;
2+
using Microsoft.Extensions.DependencyInjection;
3+
4+
namespace WebApp_OpenIDConnect_DotNet.Services
5+
{
6+
public static class Bootstrapper
7+
{
8+
public static void AddGraphService(this IServiceCollection services, IConfiguration configuration)
9+
{
10+
services.Configure<WebOptions>(configuration);
11+
}
12+
}
13+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
using Microsoft.Graph;
2+
using System;
3+
using System.Collections.Generic;
4+
using System.Linq;
5+
using System.Net.Http.Headers;
6+
using System.Threading.Tasks;
7+
8+
namespace WebApp_OpenIDConnect_DotNet.Services
9+
{
10+
public class GraphServiceClientFactory
11+
{
12+
public static async Task<GraphServiceClient> GetAuthenticatedGraphClient(Func<Task<string>> acquireAccessToken,
13+
string baseUrl = null)
14+
{
15+
// Fetch the access token
16+
string accessToken = await acquireAccessToken.Invoke();
17+
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+
}));
25+
}
26+
}
27+
}

2-WebApp-graph-user/2-1-Call-MSGraph/Services/MicrosoftGraph-Rest/Bootstrapper.cs

Lines changed: 0 additions & 15 deletions
This file was deleted.

2-WebApp-graph-user/2-1-Call-MSGraph/Services/MicrosoftGraph-Rest/GraphApiOperationService.cs

Lines changed: 0 additions & 61 deletions
This file was deleted.

2-WebApp-graph-user/2-1-Call-MSGraph/Services/MicrosoftGraph-Rest/IGraphApiOperations.cs

Lines changed: 0 additions & 10 deletions
This file was deleted.
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
namespace WebApp_OpenIDConnect_DotNet.Services.GraphOperations
1+
namespace WebApp_OpenIDConnect_DotNet.Services
22
{
33
public class WebOptions
44
{
55
public string GraphApiUrl { get; set; }
66
}
7-
}
7+
}

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

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,8 @@
88
using Microsoft.Extensions.DependencyInjection;
99
using Microsoft.Identity.Web;
1010
using Microsoft.Identity.Web.Client.TokenCacheProviders;
11-
using System;
1211
using WebApp_OpenIDConnect_DotNet.Infrastructure;
13-
using WebApp_OpenIDConnect_DotNet.Services.GraphOperations;
12+
using WebApp_OpenIDConnect_DotNet.Services;
1413

1514
namespace WebApp_OpenIDConnect_DotNet
1615
{

2-WebApp-graph-user/2-1-Call-MSGraph/Views/Home/Profile.cshtml

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -26,15 +26,28 @@
2626
}
2727
</td>
2828
</tr>
29-
@{
30-
var me = ViewData["me"] as JObject;
31-
var children = me.Properties();
32-
foreach (var child in children)
29+
@{
30+
var me = ViewData["me"] as Microsoft.Graph.User;
31+
var properties = me.GetType().GetProperties();
32+
foreach (var child in properties)
3333
{
34+
object value = child.GetValue(me);
35+
string stringRepresentation;
36+
if (!(value is string) && value is IEnumerable<string>)
37+
{
38+
stringRepresentation = "["
39+
+ string.Join(", ", (value as IEnumerable<string>).OfType<object>().Select(c => c.ToString()))
40+
+ "]";
41+
}
42+
else
43+
{
44+
stringRepresentation = value?.ToString();
45+
}
46+
3447
<tr>
35-
<td>@child.Name</td>
36-
<td>@child.Value</td>
48+
<td> @child.Name </td>
49+
<td> @stringRepresentation </td>
3750
</tr>
38-
}
51+
}
3952
}
4053
</table>

0 commit comments

Comments
 (0)