Skip to content

Commit ee35fff

Browse files
authored
Update 2-2-TokenCache (#405)
* Update bootstrap 4, frontend packages, css Update to latest Microsoft.Identity.Web C# templates Update app settings Update Nuget packages alignment with templates * Updating readme * renaming 2-2-TokenCache * fix project adding missing nuget packages
1 parent 08257b7 commit ee35fff

File tree

79 files changed

+40270
-24437
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

79 files changed

+40270
-24437
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,52 +1,76 @@
1-
using System.Diagnostics;
2-
using System.Threading.Tasks;
3-
using Microsoft.AspNetCore.Authorization;
4-
using Microsoft.AspNetCore.Mvc;
5-
using Microsoft.Identity.Web;
6-
using WebApp_OpenIDConnect_DotNet.Infrastructure;
7-
using WebApp_OpenIDConnect_DotNet.Models;
8-
using WebApp_OpenIDConnect_DotNet.Services.GraphOperations;
9-
10-
namespace WebApp_OpenIDConnect_DotNet.Controllers
11-
{
12-
[Authorize]
13-
public class HomeController : Controller
14-
{
15-
readonly ITokenAcquisition tokenAcquisition;
16-
private readonly IGraphApiOperations graphApiOperations;
17-
18-
public HomeController(ITokenAcquisition tokenAcquisition,
19-
IGraphApiOperations graphApiOperations)
20-
{
21-
this.tokenAcquisition = tokenAcquisition;
22-
this.graphApiOperations = graphApiOperations;
23-
}
24-
25-
public IActionResult Index()
26-
{
27-
return View();
28-
}
29-
30-
[AuthorizeForScopes(Scopes = new[] {Constants.ScopeUserRead})]
31-
public async Task<IActionResult> Profile()
32-
{
33-
var accessToken =
34-
await tokenAcquisition.GetAccessTokenForUserAsync(new[] {Constants.ScopeUserRead});
35-
36-
var me = await graphApiOperations.GetUserInformation(accessToken);
37-
var photo = await graphApiOperations.GetPhotoAsBase64Async(accessToken);
38-
39-
ViewData["Me"] = me;
40-
ViewData["Photo"] = photo;
41-
42-
return View();
43-
}
44-
45-
[AllowAnonymous]
46-
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
47-
public IActionResult Error()
48-
{
49-
return View(new ErrorViewModel {RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier});
50-
}
51-
}
52-
}
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Diagnostics;
4+
using System.Linq;
5+
using System.Threading.Tasks;
6+
using Microsoft.AspNetCore.Authorization;
7+
using Microsoft.Extensions.Configuration;
8+
using Microsoft.Identity.Web;
9+
using System.Net;
10+
using System.Net.Http;
11+
using Microsoft.Graph;
12+
using Microsoft.AspNetCore.Mvc;
13+
using Microsoft.Extensions.Logging;
14+
using _2_1_Call_MSGraph.Models;
15+
using System.IO;
16+
17+
namespace _2_1_Call_MSGraph.Controllers
18+
{
19+
[Authorize]
20+
public class HomeController : Controller
21+
{
22+
private readonly ILogger<HomeController> _logger;
23+
24+
private readonly GraphServiceClient _graphServiceClient;
25+
26+
public HomeController(ILogger<HomeController> logger,
27+
GraphServiceClient graphServiceClient)
28+
{
29+
_logger = logger;
30+
_graphServiceClient = graphServiceClient;
31+
}
32+
33+
[AuthorizeForScopes(ScopeKeySection = "DownstreamApi:Scopes")]
34+
public async Task<IActionResult> Index()
35+
{
36+
var user = await _graphServiceClient.Me.Request().GetAsync();
37+
ViewData["ApiResult"] = user.DisplayName;
38+
39+
return View();
40+
}
41+
42+
[AuthorizeForScopes(ScopeKeySection = "DownstreamApi:Scopes")]
43+
public async Task<IActionResult> Profile()
44+
{
45+
var me = await _graphServiceClient.Me.Request().GetAsync();
46+
ViewData["Me"] = me;
47+
48+
try
49+
{
50+
// Get user photo
51+
using (var photoStream = await _graphServiceClient.Me.Photo.Content.Request().GetAsync())
52+
{
53+
byte[] photoByte = ((MemoryStream)photoStream).ToArray();
54+
ViewData["Photo"] = Convert.ToBase64String(photoByte);
55+
}
56+
}
57+
catch (System.Exception)
58+
{
59+
ViewData["Photo"] = null;
60+
}
61+
62+
return View();
63+
}
64+
public IActionResult Privacy()
65+
{
66+
return View();
67+
}
68+
69+
[AllowAnonymous]
70+
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
71+
public IActionResult Error()
72+
{
73+
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
74+
}
75+
}
76+
}

Diff for: 2-WebApp-graph-user/2-2-TokenCache/Infrastructure/Constants.cs

-8
This file was deleted.
+11-9
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
1-
namespace WebApp_OpenIDConnect_DotNet.Models
2-
{
3-
public class ErrorViewModel
4-
{
5-
public string RequestId { get; set; }
6-
7-
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
8-
}
9-
}
1+
using System;
2+
3+
namespace _2_1_Call_MSGraph.Models
4+
{
5+
public class ErrorViewModel
6+
{
7+
public string RequestId { get; set; }
8+
9+
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
10+
}
11+
}

Diff for: 2-WebApp-graph-user/2-2-TokenCache/Program.cs

+26-20
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,26 @@
1-
using Microsoft.Extensions.Hosting;
2-
using Microsoft.AspNetCore.Hosting;
3-
4-
namespace WebApp_OpenIDConnect_DotNet
5-
{
6-
public class Program
7-
{
8-
public static void Main(string[] args)
9-
{
10-
CreateHostBuilder(args).Build().Run();
11-
}
12-
13-
public static IHostBuilder CreateHostBuilder(string[] args) =>
14-
Host.CreateDefaultBuilder(args)
15-
.ConfigureWebHostDefaults(webBuilder =>
16-
{
17-
webBuilder.UseStartup<Startup>();
18-
});
19-
}
20-
}
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Threading.Tasks;
5+
using Microsoft.AspNetCore.Hosting;
6+
using Microsoft.Extensions.Configuration;
7+
using Microsoft.Extensions.Hosting;
8+
using Microsoft.Extensions.Logging;
9+
10+
namespace _2_1_Call_MSGraph
11+
{
12+
public class Program
13+
{
14+
public static void Main(string[] args)
15+
{
16+
CreateHostBuilder(args).Build().Run();
17+
}
18+
19+
public static IHostBuilder CreateHostBuilder(string[] args) =>
20+
Host.CreateDefaultBuilder(args)
21+
.ConfigureWebHostDefaults(webBuilder =>
22+
{
23+
webBuilder.UseStartup<Startup>();
24+
});
25+
}
26+
}

Diff for: 2-WebApp-graph-user/2-2-TokenCache/README-incremental-instructions.md

+16-10
Original file line numberDiff line numberDiff line change
@@ -3,20 +3,20 @@ services: active-directory
33
platforms: dotnet
44
author: kalyankrishna1
55
level: 200
6-
client: ASP.NET Core 2.x Web App
6+
client: ASP.NET Core 3.x Web App
77
service: Microsoft Graph
88
endpoint: Microsoft identity platform
99
---
1010

11-
# Call the Microsoft Graph API from an An ASP.NET Core 2.x Web App, using Sql Server for caching tokens
11+
# Call the Microsoft Graph API from an An ASP.NET Core 3.x Web App, using Sql Server for caching tokens
1212

1313
## About this sample
1414

1515
[![Build status](https://identitydivision.visualstudio.com/IDDP/_apis/build/status/AAD%20Samples/.NET%20client%20samples/ASP.NET%20Core%20Web%20App%20tutorial)](https://identitydivision.visualstudio.com/IDDP/_build/latest?definitionId=819)
1616

1717
## Scenario
1818

19-
Starting from a .NET Core 2.2 MVC Web app that uses OpenID Connect to sign in users, this chapter of the tutorial shows how to make a call to Microsoft Graph `/me` endpoint on behalf of the signed-in user. This sample additionally provides instructions on how to use Sql Server for caching tokens.
19+
Starting from a .NET Core 3.1 MVC Web app that uses OpenID Connect to sign in users, this chapter of the tutorial shows how to make a call to Microsoft Graph `/me` endpoint on behalf of the signed-in user. This sample additionally provides instructions on how to use Sql Server for caching tokens.
2020

2121
It leverages the ASP.NET Core OpenID Connect middleware and Microsoft Authentication Library for .NET (MSAL.NET). The complexities of the library's integration with the ASP.NET Core dependency Injection patterns is encapsultated into the `Microsoft.Identity.Web` library project, which is a part of this tutorial.
2222

@@ -26,7 +26,7 @@ It leverages the ASP.NET Core OpenID Connect middleware and Microsoft Authentica
2626

2727
To run this sample, you'll need:
2828

29-
- [Visual Studio 2017](https://aka.ms/vsdownload) or just the [.NET Core SDK](https://www.microsoft.com/net/learn/get-started)
29+
- [Visual Studio 2019](https://aka.ms/vsdownload) or just the [.NET Core SDK](https://www.microsoft.com/net/learn/get-started)
3030
- An Internet connection
3131
- A Windows machine (necessary if you want to run the app on Windows)
3232
- An OS X machine (necessary if you want to run the app on Mac)
@@ -94,12 +94,18 @@ Starting from the [previous phase of the tutorial](../../2-WebApp-graph-user/2-1
9494
public void ConfigureServices(IServiceCollection services)
9595
{
9696
. . .
97-
// Token acquisition service based on MSAL.NET
98-
// and the Sql server based token cache implementation
99-
services.AddMicrosoftIdentityWebAppAuthentication(Configuration)
100-
.EnableTokenAcquisitionToCallDownstreamApi(new string[] { Constants.ScopeUserRead })
101-
.AddSqlAppTokenCache(Configuration)
102-
.AddSqlPerUserTokenCache(Configuration);
97+
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
98+
.AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"))
99+
.EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
100+
.AddMicrosoftGraph(Configuration.GetSection("DownstreamApi"))
101+
.AddDistributedTokenCaches();
102+
103+
services.AddDistributedSqlServerCache(options =>
104+
{
105+
options.ConnectionString = Configuration.GetConnectionString("TokenCacheDbConnStr");
106+
options.SchemaName = "dbo";
107+
options.TableName = "TokenCache";
108+
});
103109
```
104110

105111
The aforementioned four lines of code are explained below.

Diff for: 2-WebApp-graph-user/2-2-TokenCache/Services/MicrosoftGraph-Rest/Bootstrapper.cs

-15
This file was deleted.

Diff for: 2-WebApp-graph-user/2-2-TokenCache/Services/MicrosoftGraph-Rest/GraphApiOperationService.cs

-61
This file was deleted.

Diff for: 2-WebApp-graph-user/2-2-TokenCache/Services/MicrosoftGraph-Rest/IGraphApiOperations.cs

-10
This file was deleted.

Diff for: 2-WebApp-graph-user/2-2-TokenCache/Services/MicrosoftGraph-Rest/WebOptions.cs

-7
This file was deleted.

0 commit comments

Comments
 (0)