Skip to content

Update 2-2-TokenCache #405

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Sep 11, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
128 changes: 76 additions & 52 deletions 2-WebApp-graph-user/2-2-TokenCache/Controllers/HomeController.cs
Original file line number Diff line number Diff line change
@@ -1,52 +1,76 @@
using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Identity.Web;
using WebApp_OpenIDConnect_DotNet.Infrastructure;
using WebApp_OpenIDConnect_DotNet.Models;
using WebApp_OpenIDConnect_DotNet.Services.GraphOperations;

namespace WebApp_OpenIDConnect_DotNet.Controllers
{
[Authorize]
public class HomeController : Controller
{
readonly ITokenAcquisition tokenAcquisition;
private readonly IGraphApiOperations graphApiOperations;

public HomeController(ITokenAcquisition tokenAcquisition,
IGraphApiOperations graphApiOperations)
{
this.tokenAcquisition = tokenAcquisition;
this.graphApiOperations = graphApiOperations;
}

public IActionResult Index()
{
return View();
}

[AuthorizeForScopes(Scopes = new[] {Constants.ScopeUserRead})]
public async Task<IActionResult> Profile()
{
var accessToken =
await tokenAcquisition.GetAccessTokenForUserAsync(new[] {Constants.ScopeUserRead});

var me = await graphApiOperations.GetUserInformation(accessToken);
var photo = await graphApiOperations.GetPhotoAsBase64Async(accessToken);

ViewData["Me"] = me;
ViewData["Photo"] = photo;

return View();
}

[AllowAnonymous]
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel {RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier});
}
}
}
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Configuration;
using Microsoft.Identity.Web;
using System.Net;
using System.Net.Http;
using Microsoft.Graph;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using _2_1_Call_MSGraph.Models;
using System.IO;

namespace _2_1_Call_MSGraph.Controllers
{
[Authorize]
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;

private readonly GraphServiceClient _graphServiceClient;

public HomeController(ILogger<HomeController> logger,
GraphServiceClient graphServiceClient)
{
_logger = logger;
_graphServiceClient = graphServiceClient;
}

[AuthorizeForScopes(ScopeKeySection = "DownstreamApi:Scopes")]
public async Task<IActionResult> Index()
{
var user = await _graphServiceClient.Me.Request().GetAsync();
ViewData["ApiResult"] = user.DisplayName;

return View();
}

[AuthorizeForScopes(ScopeKeySection = "DownstreamApi:Scopes")]
public async Task<IActionResult> Profile()
{
var me = await _graphServiceClient.Me.Request().GetAsync();
ViewData["Me"] = me;

try
{
// Get user photo
using (var photoStream = await _graphServiceClient.Me.Photo.Content.Request().GetAsync())
{
byte[] photoByte = ((MemoryStream)photoStream).ToArray();
ViewData["Photo"] = Convert.ToBase64String(photoByte);
}
}
catch (System.Exception)
{
ViewData["Photo"] = null;
}

return View();
}
public IActionResult Privacy()
{
return View();
}

[AllowAnonymous]
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}

This file was deleted.

20 changes: 11 additions & 9 deletions 2-WebApp-graph-user/2-2-TokenCache/Models/ErrorViewModel.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
namespace WebApp_OpenIDConnect_DotNet.Models
{
public class ErrorViewModel
{
public string RequestId { get; set; }

public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
}
using System;

namespace _2_1_Call_MSGraph.Models
{
public class ErrorViewModel
{
public string RequestId { get; set; }

public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
}
46 changes: 26 additions & 20 deletions 2-WebApp-graph-user/2-2-TokenCache/Program.cs
Original file line number Diff line number Diff line change
@@ -1,20 +1,26 @@
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.Hosting;

namespace WebApp_OpenIDConnect_DotNet
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace _2_1_Call_MSGraph
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,20 @@ services: active-directory
platforms: dotnet
author: kalyankrishna1
level: 200
client: ASP.NET Core 2.x Web App
client: ASP.NET Core 3.x Web App
service: Microsoft Graph
endpoint: Microsoft identity platform
---

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

## About this sample

[![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)

## Scenario

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.
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.

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.

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

To run this sample, you'll need:

- [Visual Studio 2017](https://aka.ms/vsdownload) or just the [.NET Core SDK](https://www.microsoft.com/net/learn/get-started)
- [Visual Studio 2019](https://aka.ms/vsdownload) or just the [.NET Core SDK](https://www.microsoft.com/net/learn/get-started)
- An Internet connection
- A Windows machine (necessary if you want to run the app on Windows)
- An OS X machine (necessary if you want to run the app on Mac)
Expand Down Expand Up @@ -94,12 +94,18 @@ Starting from the [previous phase of the tutorial](../../2-WebApp-graph-user/2-1
public void ConfigureServices(IServiceCollection services)
{
. . .
// Token acquisition service based on MSAL.NET
// and the Sql server based token cache implementation
services.AddMicrosoftIdentityWebAppAuthentication(Configuration)
.EnableTokenAcquisitionToCallDownstreamApi(new string[] { Constants.ScopeUserRead })
.AddSqlAppTokenCache(Configuration)
.AddSqlPerUserTokenCache(Configuration);
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"))
.EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
.AddMicrosoftGraph(Configuration.GetSection("DownstreamApi"))
.AddDistributedTokenCaches();

services.AddDistributedSqlServerCache(options =>
{
options.ConnectionString = Configuration.GetConnectionString("TokenCacheDbConnStr");
options.SchemaName = "dbo";
options.TableName = "TokenCache";
});
```

The aforementioned four lines of code are explained below.
Expand Down

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

Loading