Skip to content

Commit

Permalink
Adding a sample using the Singleton Token acquisition and the GraphSe…
Browse files Browse the repository at this point in the history
…rviceClient (#159)

* Adding a sample using the Singleton Token acquisition and the GraphServiceClient

* some suggestions and add license info (#160)

* Adressing most PR comments
- GraphServiceClient instead of IGraphServiceClient per Graph SDK guidance (@darrelmiller)
- Adding the handling of the incremental consent in the Razor model
- Moving the default scopes to AddMicrosoftGraph and adding a setting to express the Graph base URL (for national clouds for instance)
- Renaming the token credential provider

Co-authored-by: jennyf19 <jeferrie@microsoft.com>
  • Loading branch information
jmprieur and jennyf19 authored May 26, 2020
1 parent 3e30d12 commit dbb91d6
Show file tree
Hide file tree
Showing 57 changed files with 39,834 additions and 0 deletions.
10 changes: 10 additions & 0 deletions Microsoft.Identity.Web.sln
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AspNetCoreMicrosoftIdentityWebProjectTemplates", "ProjectTemplates\AspNetCoreMicrosoftIdentityWebProjectTemplates.csproj", "{893905EA-94D6-4F71-957A-43B194751DC7}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "WebAppCallsGraph", "WebAppCallsGraph", "{6AD49ED7-8975-4B2F-B916-BBA8ABA280D2}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WebAppCallsMicrosoftGraph", "tests\WebAppCallsMicrosoftGraph\WebAppCallsMicrosoftGraph.csproj", "{FF8EED45-187A-4FBD-875F-334D8DC44990}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -92,6 +96,10 @@ Global
{893905EA-94D6-4F71-957A-43B194751DC7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{893905EA-94D6-4F71-957A-43B194751DC7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{893905EA-94D6-4F71-957A-43B194751DC7}.Release|Any CPU.Build.0 = Release|Any CPU
{FF8EED45-187A-4FBD-875F-334D8DC44990}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{FF8EED45-187A-4FBD-875F-334D8DC44990}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FF8EED45-187A-4FBD-875F-334D8DC44990}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FF8EED45-187A-4FBD-875F-334D8DC44990}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand All @@ -108,6 +116,8 @@ Global
{F37646FF-C346-4FF5-A111-2269952AB376} = {79310504-1334-4F14-93C4-1240913224BA}
{A9F4539F-51AB-4D98-9204-D76B336E0BE8} = {79310504-1334-4F14-93C4-1240913224BA}
{893905EA-94D6-4F71-957A-43B194751DC7} = {D845507B-00E8-4506-954E-519CBC0B9F83}
{6AD49ED7-8975-4B2F-B916-BBA8ABA280D2} = {79310504-1334-4F14-93C4-1240913224BA}
{FF8EED45-187A-4FBD-875F-334D8DC44990} = {6AD49ED7-8975-4B2F-B916-BBA8ABA280D2}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {F4FA8C4C-3251-41CC-939B-7892F5798549}
Expand Down
41 changes: 41 additions & 0 deletions tests/WebAppCallsMicrosoftGraph/MicrosoftGraphServiceExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System.Collections.Generic;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Graph;
using Microsoft.Identity.Web;

namespace WebAppCallsMicrosoftGraph
{
public static class MicrosoftGraphServiceExtensions
{
/// <summary>
/// Adds the Microsoft Graph client as a singleton.
/// </summary>
/// <param name="services">Service collection.</param>
/// <param name="configuration">Configuration for Microsoft Graph.</param>
/// <param name="initialScopes">Initial scopes.</param>
/// <param name="graphBaseUrlKey">Base URL for Microsoft graph. This can be
/// changed for instance for applications running in national clouds</param>
public static void AddMicrosoftGraph(this IServiceCollection services,
IConfiguration configuration,
IEnumerable<string> initialScopes,
string graphBaseUrlKey = "MicrosoftGraphBaseUrl")
{
// Graph base URL
string graphBaseUrl = configuration.GetValue<string>(graphBaseUrlKey);


services.AddSingleton<GraphServiceClient, GraphServiceClient>(serviceProvider =>
{
var tokenAquisitionService = serviceProvider.GetService<ITokenAcquisition>();
GraphServiceClient client = string.IsNullOrWhiteSpace(graphBaseUrl) ?
new GraphServiceClient(new TokenAcquisitionCredentialProvider(tokenAquisitionService, initialScopes)) :
new GraphServiceClient(graphBaseUrl, new TokenAcquisitionCredentialProvider(tokenAquisitionService, initialScopes));
return client;
});
}
}
}
26 changes: 26 additions & 0 deletions tests/WebAppCallsMicrosoftGraph/Pages/Error.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
@page
@model ErrorModel
@{
ViewData["Title"] = "Error";
}

<h1 class="text-danger">Error.</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>

@if (Model.ShowRequestId)
{
<p>
<strong>Request ID:</strong> <code>@Model.RequestId</code>
</p>
}

<h3>Development Mode</h3>
<p>
Swapping to the <strong>Development</strong> environment displays detailed information about the error that occurred.
</p>
<p>
<strong>The Development environment shouldn't be enabled for deployed applications.</strong>
It can result in displaying sensitive information from exceptions to end users.
For local debugging, enable the <strong>Development</strong> environment by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>
and restarting the app.
</p>
30 changes: 30 additions & 0 deletions tests/WebAppCallsMicrosoftGraph/Pages/Error.cshtml.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;

namespace WebAppCallsMicrosoftGraph.Pages
{
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public class ErrorModel : PageModel
{
public string RequestId { get; set; }

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

private readonly ILogger<ErrorModel> _logger;

public ErrorModel(ILogger<ErrorModel> logger)
{
_logger = logger;
}

public void OnGet()
{
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
}
}
}
34 changes: 34 additions & 0 deletions tests/WebAppCallsMicrosoftGraph/Pages/Index.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
@page
@model IndexModel
@{
ViewData["Title"] = "Home page";
string name = ViewData["name"] as string;
}

<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>@name, Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>

<table class="table table-striped table-condensed" style="font-family: monospace">
<tr>
<th>Property</th>
<th>Value</th>
</tr>
<tr>
<td>photo</td>
<td>
@{
if (ViewData["photo"] != null)
{
<img style="margin: 5px 0; width: 150px" src="data:image/jpeg;base64, @ViewData["photo"]" />
}
else
{
<h3>NO PHOTO</h3>
<p>Check user profile in Azure Active Directory to add a photo.</p>
}
}
</td>
</tr>
</table>
</div>
45 changes: 45 additions & 0 deletions tests/WebAppCallsMicrosoftGraph/Pages/Index.cshtml.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using Microsoft.Graph;
using Microsoft.Identity.Web;

namespace WebAppCallsMicrosoftGraph.Pages
{
[AuthorizeForScopes(Scopes = new[] { "user.read" })]
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
private readonly GraphServiceClient _graphServiceClient;

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

public async Task OnGet()
{
var user = await _graphServiceClient.Me.Request().GetAsync();

try
{
using (var photoStream = await _graphServiceClient.Me.Photo.Content.Request().GetAsync())
{
byte[] photoByte = ((MemoryStream)photoStream).ToArray();
ViewData["photo"] = Convert.ToBase64String(photoByte);
}
ViewData["name"] = user.DisplayName;
}
catch (Exception)
{
ViewData["photo"] = null;
}
}
}
}
8 changes: 8 additions & 0 deletions tests/WebAppCallsMicrosoftGraph/Pages/Privacy.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
@page
@model PrivacyModel
@{
ViewData["Title"] = "Privacy Policy";
}
<h1>@ViewData["Title"]</h1>

<p>Use this page to detail your site's privacy policy.</p>
22 changes: 22 additions & 0 deletions tests/WebAppCallsMicrosoftGraph/Pages/Privacy.cshtml.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;

namespace WebAppCallsMicrosoftGraph.Pages
{
public class PrivacyModel : PageModel
{
private readonly ILogger<PrivacyModel> _logger;

public PrivacyModel(ILogger<PrivacyModel> logger)
{
_logger = logger;
}

public void OnGet()
{
}
}
}
51 changes: 51 additions & 0 deletions tests/WebAppCallsMicrosoftGraph/Pages/Shared/_Layout.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - WebAppCallsMicrosoftGraph</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" />
</head>
<body>
<header>
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
<div class="container">
<a class="navbar-brand" asp-area="" asp-page="/Index">WebAppCallsMicrosoftGraph</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse">
<partial name="_LoginPartial" />
<ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-page="/Index">Home</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-page="/Privacy">Privacy</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="container">
<main role="main" class="pb-3">
@RenderBody()
</main>
</div>

<footer class="border-top footer text-muted">
<div class="container">
&copy; 2020 - WebAppCallsMicrosoftGraph - <a asp-area="" asp-page="/Privacy">Privacy</a>
</div>
</footer>

<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>

@await RenderSectionAsync("Scripts", required: false)
</body>
</html>
18 changes: 18 additions & 0 deletions tests/WebAppCallsMicrosoftGraph/Pages/Shared/_LoginPartial.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@

<ul class="navbar-nav">
@if (User.Identity.IsAuthenticated)
{
<li class="nav-item">
<span class="navbar-text text-dark">Hello @User.Identity.Name!</span>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="MicrosoftIdentity" asp-controller="Account" asp-action="SignOut">Sign out</a>
</li>
}
else
{
<li class="nav-item">
<a class="nav-link text-dark" asp-area="MicrosoftIdentity" asp-controller="Account" asp-action="SignIn">Sign in</a>
</li>
}
</ul>
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
3 changes: 3 additions & 0 deletions tests/WebAppCallsMicrosoftGraph/Pages/_ViewImports.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
@using WebAppCallsMicrosoftGraph
@namespace WebAppCallsMicrosoftGraph.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
3 changes: 3 additions & 0 deletions tests/WebAppCallsMicrosoftGraph/Pages/_ViewStart.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
@{
Layout = "_Layout";
}
23 changes: 23 additions & 0 deletions tests/WebAppCallsMicrosoftGraph/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;

namespace WebAppCallsMicrosoftGraph
{
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>();
});
}
}
27 changes: 27 additions & 0 deletions tests/WebAppCallsMicrosoftGraph/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:23037",
"sslPort": 44395
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"WebAppCallsMicrosoftGraph": {
"commandName": "Project",
"launchBrowser": true,
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
Loading

0 comments on commit dbb91d6

Please sign in to comment.