Skip to content

Commit e538ea2

Browse files
author
Kalyan Krishna
committed
revamped dample
1 parent 2ff32cd commit e538ea2

23 files changed

+206
-175
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,25 @@
1-
1+
22
Microsoft Visual Studio Solution File, Format Version 12.00
33
# Visual Studio Version 16
4-
VisualStudioVersion = 16.0.30413.136
4+
VisualStudioVersion = 16.0.31205.134
55
MinimumVisualStudioVersion = 10.0.40219.1
6-
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WebApp-OpenIDConnect-DotNet-graph", "WebApp-OpenIDConnect-DotNet-graph.csproj", "{76F9C1E5-3CF7-4C9A-A0EC-D15B5F11022D}"
6+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebApp-OpenIDConnect-DotNet-graph", "WebApp-OpenIDConnect-DotNet-graph.csproj", "{CD439522-E7A5-4E3D-ABB8-C1CBD75C20F4}"
77
EndProject
88
Global
99
GlobalSection(SolutionConfigurationPlatforms) = preSolution
1010
Debug|Any CPU = Debug|Any CPU
1111
Release|Any CPU = Release|Any CPU
1212
EndGlobalSection
1313
GlobalSection(ProjectConfigurationPlatforms) = postSolution
14-
{76F9C1E5-3CF7-4C9A-A0EC-D15B5F11022D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15-
{76F9C1E5-3CF7-4C9A-A0EC-D15B5F11022D}.Debug|Any CPU.Build.0 = Debug|Any CPU
16-
{76F9C1E5-3CF7-4C9A-A0EC-D15B5F11022D}.Release|Any CPU.ActiveCfg = Release|Any CPU
17-
{76F9C1E5-3CF7-4C9A-A0EC-D15B5F11022D}.Release|Any CPU.Build.0 = Release|Any CPU
14+
{CD439522-E7A5-4E3D-ABB8-C1CBD75C20F4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15+
{CD439522-E7A5-4E3D-ABB8-C1CBD75C20F4}.Debug|Any CPU.Build.0 = Debug|Any CPU
16+
{CD439522-E7A5-4E3D-ABB8-C1CBD75C20F4}.Release|Any CPU.ActiveCfg = Release|Any CPU
17+
{CD439522-E7A5-4E3D-ABB8-C1CBD75C20F4}.Release|Any CPU.Build.0 = Release|Any CPU
1818
EndGlobalSection
1919
GlobalSection(SolutionProperties) = preSolution
2020
HideSolutionNode = FALSE
2121
EndGlobalSection
2222
GlobalSection(ExtensibilityGlobals) = postSolution
23-
SolutionGuid = {AB49E34F-5B62-4F54-BAEA-C6473483C761}
23+
SolutionGuid = {758B6E79-7674-4FEE-9D22-CAB21B4284CB}
2424
EndGlobalSection
2525
EndGlobal

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

+29-16
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
1-
using CallMSGraph.Models;
1+
using Azure;
2+
using Azure.Identity;
3+
using Azure.Security.KeyVault.Secrets;
4+
using CallMSGraph.Helpers;
25
using Microsoft.AspNetCore.Authorization;
36
using Microsoft.AspNetCore.Mvc;
47
using Microsoft.Extensions.Configuration;
@@ -9,8 +12,9 @@
912
using System.Diagnostics;
1013
using System.IO;
1114
using System.Threading.Tasks;
15+
using WebApp_OpenIDConnect_DotNet_graph.Models;
1216

13-
namespace CallMSGraph.Controllers
17+
namespace WebApp_OpenIDConnect_DotNet_graph.Controllers
1418
{
1519
[Authorize]
1620
public class HomeController : Controller
@@ -38,8 +42,6 @@ public HomeController(ILogger<HomeController> logger,
3842
[AuthorizeForScopes(ScopeKeySection = "DownstreamApi:Scopes")]
3943
public IActionResult Index()
4044
{
41-
ViewData["ApiResult"] = HttpContext.User.Identity.Name;
42-
4345
return View();
4446
}
4547

@@ -69,22 +71,23 @@ public async Task<IActionResult> Profile()
6971
_consentHandler.HandleException(ex2);
7072
}
7173
}
74+
}
7275

73-
try
74-
{
75-
// Get user photo
76-
using (var photoStream = await _graphServiceClient.Me.Photo.Content.Request().GetAsync())
77-
{
78-
byte[] photoByte = ((MemoryStream)photoStream).ToArray();
79-
ViewData["Photo"] = Convert.ToBase64String(photoByte);
80-
}
81-
}
82-
catch (Exception pex)
76+
try
77+
{
78+
// Get user photo
79+
using (var photoStream = await _graphServiceClient.Me.Photo.Content.Request().GetAsync())
8380
{
84-
Console.WriteLine($"{pex}");
85-
ViewData["Photo"] = null;
81+
byte[] photoByte = ((MemoryStream)photoStream).ToArray();
82+
ViewData["Photo"] = Convert.ToBase64String(photoByte);
8683
}
8784
}
85+
catch (Exception pex)
86+
{
87+
Console.WriteLine($"{pex}");
88+
ViewData["Photo"] = null;
89+
}
90+
8891
ViewData["Me"] = currentUser;
8992
return View();
9093
}
@@ -100,5 +103,15 @@ public IActionResult Error()
100103
{
101104
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
102105
}
106+
107+
private string GetSecretFromKeyVault()
108+
{
109+
string uri = Environment.GetEnvironmentVariable("KEY_VAULT_URI");
110+
SecretClient client = new SecretClient(new Uri(uri), new DefaultAzureCredential());
111+
112+
Response<KeyVaultSecret> secret = client.GetSecretAsync("Graph-App-Secret").Result;
113+
114+
return secret.Value.Value;
115+
}
103116
}
104117
}

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

+4-1
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,11 @@
44
using System.Threading.Tasks;
55
using System.Net.Http.Headers;
66

7-
namespace CallMSGraph.Models
7+
namespace CallMSGraph.Helpers
88
{
9+
/// <summary>
10+
/// Helper methods to work with data in WWW-Authentication header
11+
/// </summary>
912
public class AuthenticationHeaderHelper
1013
{
1114
/// <summary>

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

+3-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
namespace CallMSGraph.Models
1+
using System;
2+
3+
namespace WebApp_OpenIDConnect_DotNet_graph.Models
24
{
35
public class ErrorViewModel
46
{

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

+7-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,13 @@
11
using Microsoft.AspNetCore.Hosting;
2+
using Microsoft.Extensions.Configuration;
23
using Microsoft.Extensions.Hosting;
4+
using Microsoft.Extensions.Logging;
5+
using System;
6+
using System.Collections.Generic;
7+
using System.Linq;
8+
using System.Threading.Tasks;
39

4-
namespace CallMSGraph
10+
namespace WebApp_OpenIDConnect_DotNet_graph
511
{
612
public class Program
713
{
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,27 @@
1-
{
1+
{
22
"iisSettings": {
33
"windowsAuthentication": false,
44
"anonymousAuthentication": true,
55
"iisExpress": {
6-
"applicationUrl": "http://localhost:3110/",
6+
"applicationUrl": "http://localhost:47464",
77
"sslPort": 44321
88
}
99
},
10-
"profiles": {
11-
"WebApp_OpenIDConnect_DotNet": {
12-
"commandName": "Project",
13-
"launchBrowser": true,
14-
"environmentVariables": {
15-
"ASPNETCORE_ENVIRONMENT": "Development"
16-
},
17-
"applicationUrl": "https://localhost:44321;http://localhost:3110"
10+
"profiles": {
11+
"IIS Express": {
12+
"commandName": "IISExpress",
13+
"launchBrowser": true,
14+
"environmentVariables": {
15+
"ASPNETCORE_ENVIRONMENT": "Development"
16+
}
17+
},
18+
"WebApp_OpenIDConnect_DotNet_graph": {
19+
"commandName": "Project",
20+
"launchBrowser": true,
21+
"applicationUrl": "https://localhost:44321;http://localhost:5000",
22+
"environmentVariables": {
23+
"ASPNETCORE_ENVIRONMENT": "Development"
1824
}
1925
}
20-
}
26+
}
27+
}

2-WebApp-graph-user/2-1-Call-MSGraph/Properties/serviceDependencies.json

-7
This file was deleted.

2-WebApp-graph-user/2-1-Call-MSGraph/Properties/serviceDependencies.local.json

-7
This file was deleted.

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

+3-5
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ urlFragment: active-directory-aspnetcore-webapp-openidconnect-v2
1111
description: "This sample demonstrates a ASP.NET Core Web App calling the Microsoft Graph"
1212
---
1313

14-
# # Enable your ASP.NET Core web app to sign in users and call Microsoft Graph with the Microsoft identity platform
14+
# Enable your ASP.NET Core web app to sign in users and call Microsoft Graph with the Microsoft identity platform
1515

1616
1. [Overview](#overview)
1717
1. [Scenario](#scenario)
@@ -40,7 +40,6 @@ This sample demonstrates an ASP.NET Core web app that calls the Microsoft Graph
4040

4141
![Sign in with the Microsoft identity platform and call Graph](ReadmeFiles/sign-in.png)
4242

43-
4443
## Prerequisites
4544

4645
- Either [Visual Studio](https://visualstudio.microsoft.com/downloads/) or [Visual Studio Code](https://code.visualstudio.com/download) and [.NET Core SDK](https://www.microsoft.com/net/learn/get-started)
@@ -192,7 +191,7 @@ Open the project in your IDE (like Visual Studio or Visual Studio Code) to confi
192191

193192
1. In this aspnetcore web project, first the packages `Microsoft.Identity.Web` and `Microsoft.Identity.Web.UI` were added from NuGet. These libraries are used to simplify the process of signing-in a user and acquiring tokens for Microsoft Graph.
194193

195-
1. In the **Startup.cs** file :
194+
1. Staring with the **Startup.cs** file :
196195

197196
- at the top of the file, the following two using directives were added:
198197

@@ -357,5 +356,4 @@ To provide feedback on or suggest features for Azure Active Directory, visit [Us
357356

358357
If you'd like to contribute to this sample, see [CONTRIBUTING.MD](/CONTRIBUTING.md).
359358

360-
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information, see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [[email protected]](mailto:[email protected]) with any additional questions or comments.
361-
359+
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information, see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [[email protected]](mailto:[email protected]) with any additional questions or comments.

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

+33-32
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,21 @@
1+
using Azure;
2+
using Azure.Identity;
3+
using Azure.Security.KeyVault.Secrets;
14
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
2-
using Microsoft.Identity.Web;
3-
using Microsoft.Identity.Web.UI;
45
using Microsoft.AspNetCore.Authorization;
56
using Microsoft.AspNetCore.Builder;
67
using Microsoft.AspNetCore.Hosting;
78
using Microsoft.AspNetCore.Mvc.Authorization;
89
using Microsoft.Extensions.Configuration;
910
using Microsoft.Extensions.DependencyInjection;
1011
using Microsoft.Extensions.Hosting;
12+
using Microsoft.Identity.Web;
13+
using Microsoft.Identity.Web.UI;
14+
using System;
15+
using System.Diagnostics;
16+
using System.Threading.Tasks;
1117

12-
namespace CallMSGraph
18+
namespace WebApp_OpenIDConnect_DotNet_graph
1319
{
1420
public class Startup
1521
{
@@ -26,37 +32,14 @@ public void ConfigureServices(IServiceCollection services)
2632
string[] initialScopes = Configuration.GetValue<string>("DownstreamApi:Scopes")?.Split(' ');
2733

2834
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
29-
.AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"))
35+
.AddMicrosoftIdentityWebApp(Configuration)
3036
.EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
3137
.AddMicrosoftGraph(Configuration.GetSection("DownstreamApi"))
3238
.AddInMemoryTokenCaches();
3339

34-
/*
35-
// or use a distributed Token Cache by adding
36-
.AddDistributedTokenCaches();
37-
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
40-
41-
// For instance the distributed in memory cache
42-
services.AddDistributedMemoryCache()
43-
44-
// Or a Redis cache
45-
services.AddStackExchangeRedisCache(options =>
46-
{
47-
options.Configuration = "localhost";
48-
options.InstanceName = "SampleInstance";
49-
});
50-
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-
*/
40+
// client secret is picked from KeyVault
41+
services.Configure<OpenIdConnectOptions>(OpenIdConnectDefaults.AuthenticationScheme,
42+
options => { options.ClientSecret = GetSecretFromKeyVault(); });
6043

6144
services.AddControllersWithViews(options =>
6245
{
@@ -65,8 +48,9 @@ public void ConfigureServices(IServiceCollection services)
6548
.Build();
6649
options.Filters.Add(new AuthorizeFilter(policy));
6750
});
51+
6852
services.AddRazorPages()
69-
.AddMicrosoftIdentityUI();
53+
.AddMicrosoftIdentityUI();
7054

7155
// Add the UI support to handle claims challenges
7256
services.AddServerSideBlazor()
@@ -102,5 +86,22 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
10286
endpoints.MapRazorPages();
10387
});
10488
}
89+
90+
/// <summary>
91+
/// Gets the secret from key vault via an enabled Managed Identity.
92+
/// </summary>
93+
/// <remarks>https://github.com/Azure-Samples/app-service-msi-keyvault-dotnet/blob/master/README.md</remarks>
94+
/// <returns></returns>
95+
private string GetSecretFromKeyVault()
96+
{
97+
// this should point to your vault's URI, like https://<yourkeyvault>.vault.azure.net/
98+
string uri = Environment.GetEnvironmentVariable("KEY_VAULT_URI");
99+
SecretClient client = new SecretClient(new Uri(uri), new DefaultAzureCredential());
100+
101+
// The secret name, for example if the full url to the secret is https://<yourkeyvault>.vault.azure.net/secrets/Graph-App-Secret
102+
Response<KeyVaultSecret> secret = client.GetSecretAsync("Graph-App-Secret").Result;
103+
104+
return secret.Value.Value;
105+
}
105106
}
106-
}
107+
}

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

+12-8
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,15 @@
22
ViewData["Title"] = "Home Page";
33
}
44

5-
<h1>
6-
Integrating Azure AD V2 into an ASP.NET Core web app and calling the Microsoft Graph API on behalf of the user
7-
</h1>
8-
<p>
9-
This sample shows how to build a .NET Core 3.1 MVC Web app that uses OpenID Connect to sign in users. Users can use personal accounts (including outlook.com, live.com, and others) as well as work and school accounts from any company or organization that has integrated with Azure Active Directory. It leverages the ASP.NET Core OpenID Connect middleware.
10-
</p>
11-
<img src="https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2/raw/master/2-WebApp-graph-user/2-1-Call-MSGraph/ReadmeFiles/sign-in.png
12-
"/>
5+
<div class="text-center">
6+
<h1 class="display-4">Welcome</h1>
7+
<p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
8+
</div>
9+
10+
<div class="text-center"><p>
11+
<h5 class="display-5">Enable your ASP.NET Core web app to sign in users and call Microsoft Graph with the Microsoft identity platform </h5>
12+
</p>
13+
<img src="https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2/raw/master/2-WebApp-graph-user/2-1-Call-MSGraph/ReadmeFiles/sign-in.png" />
14+
<p>Integrate an ASP.NET Core web app with the Microsoft Identity platform and calls Microsoft Graph API for the signed-in user</p>
15+
</div>
16+

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

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
@{
1+
@{
22
ViewData["Title"] = "Privacy Policy";
33
}
44
<h1>@ViewData["Title"]</h1>

0 commit comments

Comments
 (0)