Skip to content

Commit 7d2d8ed

Browse files
authored
small fixes to 2-1-Call-MSGraph readme and small code clean up (#410)
* code clean up * removing unused headers * Fixing readme 2-1-Call-MSGraph * some formatting
1 parent 246eea2 commit 7d2d8ed

File tree

5 files changed

+52
-75
lines changed

5 files changed

+52
-75
lines changed

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

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,8 @@
11
using System;
2-
using System.Collections.Generic;
32
using System.Diagnostics;
4-
using System.Linq;
53
using System.Threading.Tasks;
64
using Microsoft.AspNetCore.Authorization;
7-
using Microsoft.Extensions.Configuration;
85
using Microsoft.Identity.Web;
9-
using System.Net;
10-
using System.Net.Http;
116
using Microsoft.Graph;
127
using Microsoft.AspNetCore.Mvc;
138
using Microsoft.Extensions.Logging;
@@ -26,9 +21,9 @@ public class HomeController : Controller
2621
public HomeController(ILogger<HomeController> logger,
2722
GraphServiceClient graphServiceClient)
2823
{
29-
_logger = logger;
24+
_logger = logger;
3025
_graphServiceClient = graphServiceClient;
31-
}
26+
}
3227

3328
[AuthorizeForScopes(ScopeKeySection = "DownstreamApi:Scopes")]
3429
public async Task<IActionResult> Index()

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

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
using System;
2-
31
namespace _2_1_Call_MSGraph.Models
42
{
53
public class ErrorViewModel

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

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,5 @@
1-
using System;
2-
using System.Collections.Generic;
3-
using System.Linq;
4-
using System.Threading.Tasks;
51
using Microsoft.AspNetCore.Hosting;
6-
using Microsoft.Extensions.Configuration;
72
using Microsoft.Extensions.Hosting;
8-
using Microsoft.Extensions.Logging;
93

104
namespace _2_1_Call_MSGraph
115
{

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

Lines changed: 22 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -100,9 +100,14 @@ After the following lines in the ConfigureServices(IServiceCollection services)
100100
public void ConfigureServices(IServiceCollection services)
101101
{
102102
. . .
103-
services.AddMicrosoftIdentityWebAppAuthentication(Configuration)
104-
.EnableTokenAcquisitionToCallDownstreamApi(new string[] { Constants.ScopeUserRead })
105-
.AddInMemoryTokenCaches();
103+
string[] initialScopes = Configuration.GetValue<string>("DownstreamApi:Scopes")?.Split(' ');
104+
105+
// Add Graph
106+
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
107+
.AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"))
108+
.EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
109+
.AddMicrosoftGraph(Configuration.GetSection("DownstreamApi"))
110+
.AddInMemoryTokenCaches();
106111
```
107112

108113
The two new lines of code:
@@ -154,11 +159,15 @@ Add the `Services\*.cs` files. The `GraphServiceClientFactory.cs` returns a `Gra
154159
155160
### Update the `Startup.cs` file to enable the Microsoft Graph custom service
156161

157-
Still in the `Startup.cs` file, add the following lines just after the following. This lines ensures that the GraphAPIService benefits from the optimized `HttpClient` management by ASP.NET Core.
162+
Still in the `Startup.cs` file, add the following `AddMicrosoftGraph` extension method. This lines ensures that the GraphAPIService benefits from the optimized `HttpClient` management by ASP.NET Core.
158163

159164
```CSharp
160165
// Add Graph
161-
services.AddGraphService(Configuration);
166+
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
167+
.AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"))
168+
.EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
169+
.AddMicrosoftGraph(Configuration.GetSection("DownstreamApi"))
170+
.AddInMemoryTokenCaches();
162171
```
163172

164173
### Change the controller code to acquire a token and call Microsoft Graph
@@ -168,32 +177,29 @@ In the `Controllers\HomeController.cs`file:
168177
1. Add a constructor to HomeController, making the ITokenAcquisition service available (used by the ASP.NET dependency injection mechanism)
169178

170179
```CSharp
171-
readonly ITokenAcquisition tokenAcquisition;
172-
readonly WebOptions webOptions;
180+
private readonly GraphServiceClient _graphServiceClient;
173181

174-
public HomeController(ITokenAcquisition tokenAcquisition, IOptions<WebOptions> webOptionValue)
182+
public HomeController(ILogger<HomeController> logger,
183+
GraphServiceClient graphServiceClient)
175184
{
176-
this.tokenAcquisition = tokenAcquisition;
177-
this.webOptions = webOptionValue.Value;
185+
_logger = logger;
186+
_graphServiceClient = graphServiceClient;
178187
}
179188
```
180189

181190
1. Add a `Profile()` action so that it calls the Microsoft Graph *me* endpoint. In case a token cannot be acquired, a challenge is attempted to re-sign-in the user, and have them consent to the requested scopes. This is expressed declaratively by the `AuthorizeForScopes`attribute. This attribute is part of the `Microsoft.Identity.Web` project and automatically manages incremental consent.
182191

183192
```CSharp
184-
[AuthorizeForScopes(Scopes = new[] { Constants.ScopeUserRead })]
193+
[AuthorizeForScopes(ScopeKeySection = "DownstreamApi:Scopes")]
185194
public async Task<IActionResult> Profile()
186195
{
187-
// Initialize the GraphServiceClient.
188-
Graph::GraphServiceClient graphClient = GetGraphServiceClient(new[] { Constants.ScopeUserRead });
189-
190-
var me = await graphClient.Me.Request().GetAsync();
196+
var me = await _graphServiceClient.Me.Request().GetAsync();
191197
ViewData["Me"] = me;
192198

193199
try
194200
{
195201
// Get user photo
196-
using (var photoStream = await graphClient.Me.Photo.Content.Request().GetAsync())
202+
using (var photoStream = await _graphServiceClient.Me.Photo.Content.Request().GetAsync())
197203
{
198204
byte[] photoByte = ((MemoryStream)photoStream).ToArray();
199205
ViewData["Photo"] = Convert.ToBase64String(photoByte);
@@ -206,15 +212,6 @@ public async Task<IActionResult> Profile()
206212

207213
return View();
208214
}
209-
210-
private Graph::GraphServiceClient GetGraphServiceClient(string[] scopes)
211-
{
212-
return GraphServiceClientFactory.GetAuthenticatedGraphClient(async () =>
213-
{
214-
string result = await tokenAcquisition.GetAccessTokenOnBehalfOfUserAsync(scopes);
215-
return result;
216-
}, webOptions.GraphApiUrl);
217-
}
218215
```
219216

220217
### Add a Profile view to display the *me* object

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

Lines changed: 28 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,13 @@
1-
using System;
2-
using System.Collections.Generic;
3-
using System.Linq;
4-
using System.Threading.Tasks;
5-
using Microsoft.AspNetCore.Authentication;
61
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
72
using Microsoft.Identity.Web;
83
using Microsoft.Identity.Web.UI;
94
using Microsoft.AspNetCore.Authorization;
105
using Microsoft.AspNetCore.Builder;
116
using Microsoft.AspNetCore.Hosting;
12-
using Microsoft.AspNetCore.HttpsPolicy;
137
using Microsoft.AspNetCore.Mvc.Authorization;
148
using Microsoft.Extensions.Configuration;
159
using Microsoft.Extensions.DependencyInjection;
1610
using Microsoft.Extensions.Hosting;
17-
using Microsoft.Graph;
1811

1912
namespace _2_1_Call_MSGraph
2013
{
@@ -33,37 +26,37 @@ public void ConfigureServices(IServiceCollection services)
3326
string[] initialScopes = Configuration.GetValue<string>("DownstreamApi:Scopes")?.Split(' ');
3427

3528
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
36-
.AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"))
37-
.EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
38-
.AddMicrosoftGraph(Configuration.GetSection("DownstreamApi"))
39-
.AddInMemoryTokenCaches();
29+
.AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"))
30+
.EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
31+
.AddMicrosoftGraph(Configuration.GetSection("DownstreamApi"))
32+
.AddInMemoryTokenCaches();
4033

41-
/*
42-
// or use a distributed Token Cache by adding
43-
.AddDistributedTokenCaches();
34+
/*
35+
// or use a distributed Token Cache by adding
36+
.AddDistributedTokenCaches();
4437
45-
// and then choose your implementation.
46-
// See https://docs.microsoft.com/en-us/aspnet/core/performance/caching/distributed?view=aspnetcore-2.2#distributed-memory-cache
38+
// and then choose your implementation.
39+
// See https://docs.microsoft.com/en-us/aspnet/core/performance/caching/distributed?view=aspnetcore-2.2#distributed-memory-cache
4740
48-
// For instance the distributed in memory cache
49-
services.AddDistributedMemoryCache()
41+
// For instance the distributed in memory cache
42+
services.AddDistributedMemoryCache()
5043
51-
// Or a Redis cache
52-
services.AddStackExchangeRedisCache(options =>
53-
{
54-
options.Configuration = "localhost";
55-
options.InstanceName = "SampleInstance";
56-
});
44+
// Or a Redis cache
45+
services.AddStackExchangeRedisCache(options =>
46+
{
47+
options.Configuration = "localhost";
48+
options.InstanceName = "SampleInstance";
49+
});
5750
58-
// Or even a SQL Server token cache
59-
services.AddDistributedSqlServerCache(options =>
60-
{
61-
options.ConnectionString =
62-
_config["DistCache_ConnectionString"];
63-
options.SchemaName = "dbo";
64-
options.TableName = "TestCache";
65-
});
66-
*/
51+
// Or even a SQL Server token cache
52+
services.AddDistributedSqlServerCache(options =>
53+
{
54+
options.ConnectionString =
55+
_config["DistCache_ConnectionString"];
56+
options.SchemaName = "dbo";
57+
options.TableName = "TestCache";
58+
});
59+
*/
6760

6861
services.AddControllersWithViews(options =>
6962
{
@@ -72,8 +65,8 @@ public void ConfigureServices(IServiceCollection services)
7265
.Build();
7366
options.Filters.Add(new AuthorizeFilter(policy));
7467
});
75-
services.AddRazorPages()
76-
.AddMicrosoftIdentityUI();
68+
services.AddRazorPages()
69+
.AddMicrosoftIdentityUI();
7770
}
7871

7972
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.

0 commit comments

Comments
 (0)