From e1e46292a73e7b877e515e5c0926d2fe9f3e12ea Mon Sep 17 00:00:00 2001 From: Jennyf19 Date: Thu, 21 Jan 2021 16:51:14 -0800 Subject: [PATCH 01/10] initial commit to add graph & api call to worker2 --- .../.template.config/template.json | 35 +++++++++++++++++-- .../templates/Worker-CSharp/Startup.cs | 27 +++++++++++--- .../ExceptionHandlingTest.cs | 29 +++++++++++++++ 3 files changed, 85 insertions(+), 6 deletions(-) create mode 100644 tests/Microsoft.Identity.Web.Test/ExceptionHandlingTest.cs diff --git a/ProjectTemplates/templates/Worker-CSharp/.template.config/template.json b/ProjectTemplates/templates/Worker-CSharp/.template.config/template.json index 73e7ca7dc..a27e13529 100644 --- a/ProjectTemplates/templates/Worker-CSharp/.template.config/template.json +++ b/ProjectTemplates/templates/Worker-CSharp/.template.config/template.json @@ -160,10 +160,41 @@ } }, "skipRestore": { + "type": "parameter", + "datatype": "bool", + "description": "If specified, skips the automatic restore of the project on create.", + "defaultValue": "false" + }, + "CalledApiUrl": { + "type": "parameter", + "datatype": "string", + "replaces": "[WebApiUrl]", + "defaultValue": "https://graph.microsoft.com/v1.0", + "description": "URL of the API to call from the web app. This option only applies if --auth SingleOrg or --auth IndividualB2C is specified." + }, + "CallsMicrosoftGraph": { "type": "parameter", "datatype": "bool", - "description": "If specified, skips the automatic restore of the project on create.", - "defaultValue": "false" + "defaultValue": "false", + "description": "Specifies if the web app calls Microsoft Graph. This option only applies if --auth SingleOrg is specified." + }, + "CalledApiScopes": { + "type": "parameter", + "datatype": "string", + "replaces": "user.read", + "description": "Scopes to request to call the API from the web app. This option only applies if --auth SingleOrg or --auth IndividualB2C is specified." + }, + "GenerateApi": { + "type": "computed", + "value": "((IndividualB2CAuth || OrganizationalAuth) && (CalledApiUrl != \"https://graph.microsoft.com/v1.0\" || CalledApiScopes != \"user.read\"))" + }, + "GenerateGraph": { + "type": "computed", + "value": "(OrganizationalAuth && CallsMicrosoftGraph)" + }, + "GenerateApiOrGraph": { + "type": "computed", + "value": "(GenerateApi || GenerateGraph)" } }, "primaryOutputs": [ diff --git a/ProjectTemplates/templates/Worker-CSharp/Startup.cs b/ProjectTemplates/templates/Worker-CSharp/Startup.cs index b9a3bfd53..57e20cb21 100644 --- a/ProjectTemplates/templates/Worker-CSharp/Startup.cs +++ b/ProjectTemplates/templates/Worker-CSharp/Startup.cs @@ -9,6 +9,9 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.AspNetCore.Http; +#if (GenerateGraph) +using Microsoft.Graph; +#endif namespace Company.Application1 { @@ -28,15 +31,31 @@ public void ConfigureServices(IServiceCollection services) #if (OrganizationalAuth) services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) +#if (GenerateApiOrGraph) + .AddMicrosoftIdentityWebApi(Configuration.GetSection("AzureAd")) + .EnableTokenAcquisitionToCallDownstreamApi() +#if (GenerateApi) + .AddDownstreamWebApi("DownstreamApi", Configuration.GetSection("DownstreamApi")) +#endif +#if (GenerateGraph) + .AddMicrosoftGraph(Configuration.GetSection("DownstreamApi")) +#endif + .AddInMemoryTokenCaches(); +#else .AddMicrosoftIdentityWebApi(Configuration.GetSection("AzureAd")); - - services.AddAuthorization(); +#endif #elif (IndividualB2CAuth) services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) +#if (GenerateApi) + .AddMicrosoftIdentityWebApi(Configuration.GetSection("AzureAdB2C")) + .EnableTokenAcquisitionToCallDownstreamApi() + .AddDownstreamWebApi("DownstreamApi", Configuration.GetSection("DownstreamApi")) + .AddInMemoryTokenCaches(); +#else .AddMicrosoftIdentityWebApi(Configuration.GetSection("AzureAdB2C")); - - services.AddAuthorization(); #endif +#endif + services.AddAuthorization(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. diff --git a/tests/Microsoft.Identity.Web.Test/ExceptionHandlingTest.cs b/tests/Microsoft.Identity.Web.Test/ExceptionHandlingTest.cs new file mode 100644 index 000000000..8c04a0897 --- /dev/null +++ b/tests/Microsoft.Identity.Web.Test/ExceptionHandlingTest.cs @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using Microsoft.Identity.Client; +using Xunit; + +namespace Microsoft.Identity.Web.Test +{ + public class ExceptionHandlingTest + { + [Fact] + public void AuthorizeForScopesAttribute_FindMsalUiRequiredExceptionIfAny_Tests() + { + MsalUiRequiredException msalUiRequiredException = new MsalUiRequiredException("code", "message"); + + MsalUiRequiredException result = AuthorizeForScopesAttribute.FindMsalUiRequiredExceptionIfAny(msalUiRequiredException); + Assert.Equal(result, msalUiRequiredException); + + Exception ex = new Exception("message", msalUiRequiredException); + result = AuthorizeForScopesAttribute.FindMsalUiRequiredExceptionIfAny(ex); + Assert.Equal(result, msalUiRequiredException); + + Exception ex2 = new Exception("message", ex); + result = AuthorizeForScopesAttribute.FindMsalUiRequiredExceptionIfAny(ex2); + Assert.Equal(result, msalUiRequiredException); + } + } +} From 385f4ddd8f288e3c7ff9fcb0667aa69ac80e87bb Mon Sep 17 00:00:00 2001 From: Jennyf19 Date: Thu, 21 Jan 2021 17:05:05 -0800 Subject: [PATCH 02/10] remove renamed file --- .../ExceptionHandlingTest.cs | 29 ------------------- 1 file changed, 29 deletions(-) delete mode 100644 tests/Microsoft.Identity.Web.Test/ExceptionHandlingTest.cs diff --git a/tests/Microsoft.Identity.Web.Test/ExceptionHandlingTest.cs b/tests/Microsoft.Identity.Web.Test/ExceptionHandlingTest.cs deleted file mode 100644 index 8c04a0897..000000000 --- a/tests/Microsoft.Identity.Web.Test/ExceptionHandlingTest.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; -using Microsoft.Identity.Client; -using Xunit; - -namespace Microsoft.Identity.Web.Test -{ - public class ExceptionHandlingTest - { - [Fact] - public void AuthorizeForScopesAttribute_FindMsalUiRequiredExceptionIfAny_Tests() - { - MsalUiRequiredException msalUiRequiredException = new MsalUiRequiredException("code", "message"); - - MsalUiRequiredException result = AuthorizeForScopesAttribute.FindMsalUiRequiredExceptionIfAny(msalUiRequiredException); - Assert.Equal(result, msalUiRequiredException); - - Exception ex = new Exception("message", msalUiRequiredException); - result = AuthorizeForScopesAttribute.FindMsalUiRequiredExceptionIfAny(ex); - Assert.Equal(result, msalUiRequiredException); - - Exception ex2 = new Exception("message", ex); - result = AuthorizeForScopesAttribute.FindMsalUiRequiredExceptionIfAny(ex2); - Assert.Equal(result, msalUiRequiredException); - } - } -} From f2b66f79da4305e9f8022290e4fae9cada046568 Mon Sep 17 00:00:00 2001 From: Jennyf19 Date: Fri, 22 Jan 2021 13:01:50 -0800 Subject: [PATCH 03/10] more updates to worker2 --- .../.template.config/dotnetcli.host.json | 14 +++- .../Worker-CSharp/Company.Application1.csproj | 4 +- .../templates/Worker-CSharp/Worker.cs | 82 ++++++++++++++++++- 3 files changed, 97 insertions(+), 3 deletions(-) diff --git a/ProjectTemplates/templates/Worker-CSharp/.template.config/dotnetcli.host.json b/ProjectTemplates/templates/Worker-CSharp/.template.config/dotnetcli.host.json index 665f91c53..a7609133d 100644 --- a/ProjectTemplates/templates/Worker-CSharp/.template.config/dotnetcli.host.json +++ b/ProjectTemplates/templates/Worker-CSharp/.template.config/dotnetcli.host.json @@ -41,7 +41,19 @@ "shortName": "" }, "ExcludeLaunchSettings": { - "longName": "exclude-launch-settings", + "longName": "exclude-launch-settings", + "shortName": "" + }, + "CalledApiUrl": { + "longName": "called-api-url", + "shortName": "" + }, + "CalledApiScopes": { + "longName": "called-api-scopes", + "shortName": "" + }, + "CallsMicrosoftGraph": { + "longName": "calls-graph", "shortName": "" } }, diff --git a/ProjectTemplates/templates/Worker-CSharp/Company.Application1.csproj b/ProjectTemplates/templates/Worker-CSharp/Company.Application1.csproj index 5d4ffb545..e8e1a6ea5 100644 --- a/ProjectTemplates/templates/Worker-CSharp/Company.Application1.csproj +++ b/ProjectTemplates/templates/Worker-CSharp/Company.Application1.csproj @@ -13,7 +13,9 @@ - + + + diff --git a/ProjectTemplates/templates/Worker-CSharp/Worker.cs b/ProjectTemplates/templates/Worker-CSharp/Worker.cs index 07d43ffaa..2231ceb74 100644 --- a/ProjectTemplates/templates/Worker-CSharp/Worker.cs +++ b/ProjectTemplates/templates/Worker-CSharp/Worker.cs @@ -3,8 +3,21 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; -using Microsoft.Extensions.Hosting; +#if (!NoAuth) +using Microsoft.AspNetCore.Authorization; +#endif +#if (GenerateApi) +using Microsoft.Extensions.Configuration; +using Microsoft.Identity.Web; +using System.Net.Http; +#endif +#if (GenerateGraph) +using Microsoft.Graph; +#endif using Microsoft.Extensions.Logging; +#if (OrganizationalAuth || IndividualB2CAuth) +using Microsoft.Identity.Web.Resource; +#endif namespace Company.Application1 { @@ -12,6 +25,69 @@ public class Worker : BackgroundService { private readonly ILogger _logger; +#if (!NoAuth) + // The web API will only accept tokens 1) for users, and 2) having the "api-scope" scope for this API + static readonly string[] scopeRequiredByApi = new string[] { "api-scope" }; +#endif + + +#if (GenerateApi) + private readonly IDownstreamWebApi _downstreamWebApi; + + public Worker(ILogger logger, + IDownstreamWebApi downstreamWebApi) + { + _logger = logger; + _downstreamWebApi = downstreamWebApi; + } + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + HttpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi); + + while (!stoppingToken.IsCancellationRequested) + { + _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now); + await Task.Delay(1000, stoppingToken); + } + + using var response = await _downstreamWebApi.CallWebApiForUserAsync("DownstreamApi").ConfigureAwait(false); + if (response.StatusCode == System.Net.HttpStatusCode.OK) + { + var apiResult = await response.Content.ReadAsStringAsync().ConfigureAwait(false); + // Do something + } + else + { + var error = await response.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new HttpRequestException($"Invalid status code in the HttpResponseMessage: {response.StatusCode}: {error}"); + } + } + +#elseif (GenerateGraph) + private readonly GraphServiceClient _graphServiceClient; + + public Worker(ILogger logger, + GraphServiceClient graphServiceClient) + { + _logger = logger; + _graphServiceClient = graphServiceClient; + } + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + HttpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi); + + while (!stoppingToken.IsCancellationRequested) + { + _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now); + await Task.Delay(1000, stoppingToken); + } + + var user = await _graphServiceClient.Me.Request().GetAsync(); + } + +#else public Worker(ILogger logger) { _logger = logger; @@ -19,11 +95,15 @@ public Worker(ILogger logger) protected override async Task ExecuteAsync(CancellationToken stoppingToken) { +#if (!NoAuth) + HttpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi); +#endif while (!stoppingToken.IsCancellationRequested) { _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now); await Task.Delay(1000, stoppingToken); } } +#endif } } From f0cd6582f6992fa18a0d3edd1116fb1409991315 Mon Sep 17 00:00:00 2001 From: Jennyf19 Date: Fri, 22 Jan 2021 13:04:29 -0800 Subject: [PATCH 04/10] update test templates --- ProjectTemplates/test-templates-from-nuget.bat | 15 +++++++++++++++ ProjectTemplates/test-templates.bat | 14 ++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/ProjectTemplates/test-templates-from-nuget.bat b/ProjectTemplates/test-templates-from-nuget.bat index 74560b0b9..ce9c8200d 100644 --- a/ProjectTemplates/test-templates-from-nuget.bat +++ b/ProjectTemplates/test-templates-from-nuget.bat @@ -305,6 +305,21 @@ cd worker2-b2c dotnet new worker2 --auth IndividualB2C dotnet sln ..\..\tests.sln add worker2-b2c.csproj cd .. + +echo "Test worker2, single-org, calling microsoft graph" +mkdir worker2-singleorg-callsgraph +cd worker2-singleorg-callsgraph +dotnet new worker2 --auth SingleOrg --calls-graph +dotnet sln ..\..\tests.sln add worker2-singleorg-callsgraph.csproj +cd .. + +echo "Test worker2, single-org, calling a downstream web api" +mkdir worker2-singleorg-callswebapi +cd worker2-singleorg-callswebapi +dotnet new worker2 --auth SingleOrg --called-api-url "https://graph.microsoft.com/beta/me" --called-api-scopes "user.read" +dotnet sln ..\..\tests.sln add worker2-singleorg-callswebapi.csproj +cd .. + cd .. echo "Configure the applications" diff --git a/ProjectTemplates/test-templates.bat b/ProjectTemplates/test-templates.bat index 467899696..03061ed30 100644 --- a/ProjectTemplates/test-templates.bat +++ b/ProjectTemplates/test-templates.bat @@ -302,6 +302,20 @@ dotnet new worker2 --auth IndividualB2C dotnet sln ..\..\tests.sln add worker2-b2c.csproj cd .. +echo "Test worker2, single-org, calling microsoft graph" +mkdir worker2-singleorg-callsgraph +cd worker2-singleorg-callsgraph +dotnet new worker2 --auth SingleOrg --calls-graph +dotnet sln ..\..\tests.sln add worker2-singleorg-callsgraph.csproj +cd .. + +echo "Test worker2, single-org, calling a downstream web api" +mkdir worker2-singleorg-callswebapi +cd worker2-singleorg-callswebapi +dotnet new worker2 --auth SingleOrg --called-api-url "https://graph.microsoft.com/beta/me" --called-api-scopes "user.read" +dotnet sln ..\..\tests.sln add worker2-singleorg-callswebapi.csproj +cd .. + cd .. echo "Configure the applications" From 1a23fb0f9ab0786d883d1acde3a090f4eb512460 Mon Sep 17 00:00:00 2001 From: Jennyf19 Date: Fri, 22 Jan 2021 13:31:20 -0800 Subject: [PATCH 05/10] fix usings --- ProjectTemplates/templates/Worker-CSharp/Worker.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/ProjectTemplates/templates/Worker-CSharp/Worker.cs b/ProjectTemplates/templates/Worker-CSharp/Worker.cs index 2231ceb74..894d577f7 100644 --- a/ProjectTemplates/templates/Worker-CSharp/Worker.cs +++ b/ProjectTemplates/templates/Worker-CSharp/Worker.cs @@ -5,6 +5,7 @@ using System.Threading.Tasks; #if (!NoAuth) using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; #endif #if (GenerateApi) using Microsoft.Extensions.Configuration; @@ -14,6 +15,7 @@ #if (GenerateGraph) using Microsoft.Graph; #endif +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; #if (OrganizationalAuth || IndividualB2CAuth) using Microsoft.Identity.Web.Resource; From 140ef1f54be9a15b990b76626b186caf4a3c5065 Mon Sep 17 00:00:00 2001 From: Jennyf19 Date: Fri, 22 Jan 2021 13:33:44 -0800 Subject: [PATCH 06/10] one more using --- ProjectTemplates/templates/Worker-CSharp/Worker.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/ProjectTemplates/templates/Worker-CSharp/Worker.cs b/ProjectTemplates/templates/Worker-CSharp/Worker.cs index 894d577f7..045cf4e31 100644 --- a/ProjectTemplates/templates/Worker-CSharp/Worker.cs +++ b/ProjectTemplates/templates/Worker-CSharp/Worker.cs @@ -10,6 +10,7 @@ #if (GenerateApi) using Microsoft.Extensions.Configuration; using Microsoft.Identity.Web; +using System.Net; using System.Net.Http; #endif #if (GenerateGraph) From 324a140588131a3bcbe2d48b54a8308d391db94d Mon Sep 17 00:00:00 2001 From: Jennyf19 Date: Sat, 23 Jan 2021 10:58:21 -0800 Subject: [PATCH 07/10] move api calls to greeterService --- .../templates/Worker-CSharp/GreeterService.cs | 79 +++++++++++++++++- .../templates/Worker-CSharp/Worker.cs | 83 ------------------- 2 files changed, 75 insertions(+), 87 deletions(-) diff --git a/ProjectTemplates/templates/Worker-CSharp/GreeterService.cs b/ProjectTemplates/templates/Worker-CSharp/GreeterService.cs index f17f0825d..1762ef204 100644 --- a/ProjectTemplates/templates/Worker-CSharp/GreeterService.cs +++ b/ProjectTemplates/templates/Worker-CSharp/GreeterService.cs @@ -2,9 +2,19 @@ using Grpc.Core; #if (!NoAuth) using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +#endif +#if (GenerateApi) +using Microsoft.Extensions.Configuration; +using Microsoft.Identity.Web; +using System.Net; +using System.Net.Http; +#endif +#if (GenerateGraph) +using Microsoft.Graph; #endif using Microsoft.Extensions.Logging; -#if (OrganizationalAuth || IndividualB2CAuth) +#if (!NoAuth) using Microsoft.Identity.Web.Resource; #endif @@ -13,19 +23,79 @@ namespace Company.Application1 public class GreeterService : Greeter.GreeterBase { private readonly ILogger _logger; - public GreeterService(ILogger logger) + +#if (!NoAuth) + // The web API will only accept tokens 1) for users, and 2) having the "api-scope" scope for this API + static readonly string[] scopeRequiredByApi = new string[] { "api-scope" }; +#endif + +#if (GenerateApi) + private readonly IDownstreamWebApi _downstreamWebApi; + + public GreeterService(ILogger logger, + IDownstreamWebApi downstreamWebApi) { _logger = logger; + _downstreamWebApi = downstreamWebApi; } - static string[] scopeRequiredByAPI = new string[] { "access_as_user" }; + [Authorize] + public override Task SayHello(HelloRequest request, ServerCallContext context) + { + var httpContext = context.GetHttpContext(); + httpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByAPI); + using var response = await _downstreamWebApi.CallWebApiForUserAsync("DownstreamApi").ConfigureAwait(false); + if (response.StatusCode == System.Net.HttpStatusCode.OK) + { + var apiResult = await response.Content.ReadAsStringAsync().ConfigureAwait(false); + // Do something with apiResult + } + else + { + var error = await response.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new HttpRequestException($"Invalid status code in the HttpResponseMessage: {response.StatusCode}: {error}"); + } + + return Task.FromResult(new HelloReply + { + Message = "Hello " + request.Name + }); + } + +# elseif (GenerateGraph) + private readonly GraphServiceClient _graphServiceClient; + + public GreeterService(ILogger logger, + GraphServiceClient graphServiceClient) + { + _logger = logger; + _graphServiceClient = graphServiceClient; + } + + [Authorize] + public override Task SayHello(HelloRequest request, ServerCallContext context) + { + var httpContext = context.GetHttpContext(); + httpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByAPI); + var user = await _graphServiceClient.Me.Request().GetAsync(); + + return Task.FromResult(new HelloReply + { + Message = "Hello " + user.Name + }); + } +#else + public GreeterService(ILogger logger) + { + _logger = logger; + } #if (!NoAuth) [Authorize] #endif public override Task SayHello(HelloRequest request, ServerCallContext context) { -#if (OrganizationalAuth || IndividualB2CAuth) +#if (!NoAuth) var httpContext = context.GetHttpContext(); httpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByAPI); #endif @@ -34,5 +104,6 @@ public override Task SayHello(HelloRequest request, ServerCallContex Message = "Hello " + request.Name }); } +#endif } } diff --git a/ProjectTemplates/templates/Worker-CSharp/Worker.cs b/ProjectTemplates/templates/Worker-CSharp/Worker.cs index 045cf4e31..07d43ffaa 100644 --- a/ProjectTemplates/templates/Worker-CSharp/Worker.cs +++ b/ProjectTemplates/templates/Worker-CSharp/Worker.cs @@ -3,24 +3,8 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; -#if (!NoAuth) -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Http; -#endif -#if (GenerateApi) -using Microsoft.Extensions.Configuration; -using Microsoft.Identity.Web; -using System.Net; -using System.Net.Http; -#endif -#if (GenerateGraph) -using Microsoft.Graph; -#endif using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; -#if (OrganizationalAuth || IndividualB2CAuth) -using Microsoft.Identity.Web.Resource; -#endif namespace Company.Application1 { @@ -28,69 +12,6 @@ public class Worker : BackgroundService { private readonly ILogger _logger; -#if (!NoAuth) - // The web API will only accept tokens 1) for users, and 2) having the "api-scope" scope for this API - static readonly string[] scopeRequiredByApi = new string[] { "api-scope" }; -#endif - - -#if (GenerateApi) - private readonly IDownstreamWebApi _downstreamWebApi; - - public Worker(ILogger logger, - IDownstreamWebApi downstreamWebApi) - { - _logger = logger; - _downstreamWebApi = downstreamWebApi; - } - - protected override async Task ExecuteAsync(CancellationToken stoppingToken) - { - HttpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi); - - while (!stoppingToken.IsCancellationRequested) - { - _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now); - await Task.Delay(1000, stoppingToken); - } - - using var response = await _downstreamWebApi.CallWebApiForUserAsync("DownstreamApi").ConfigureAwait(false); - if (response.StatusCode == System.Net.HttpStatusCode.OK) - { - var apiResult = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - // Do something - } - else - { - var error = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new HttpRequestException($"Invalid status code in the HttpResponseMessage: {response.StatusCode}: {error}"); - } - } - -#elseif (GenerateGraph) - private readonly GraphServiceClient _graphServiceClient; - - public Worker(ILogger logger, - GraphServiceClient graphServiceClient) - { - _logger = logger; - _graphServiceClient = graphServiceClient; - } - - protected override async Task ExecuteAsync(CancellationToken stoppingToken) - { - HttpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi); - - while (!stoppingToken.IsCancellationRequested) - { - _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now); - await Task.Delay(1000, stoppingToken); - } - - var user = await _graphServiceClient.Me.Request().GetAsync(); - } - -#else public Worker(ILogger logger) { _logger = logger; @@ -98,15 +19,11 @@ public Worker(ILogger logger) protected override async Task ExecuteAsync(CancellationToken stoppingToken) { -#if (!NoAuth) - HttpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi); -#endif while (!stoppingToken.IsCancellationRequested) { _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now); await Task.Delay(1000, stoppingToken); } } -#endif } } From a554be32d7a2b41ff437823a461e7c79599c9b69 Mon Sep 17 00:00:00 2001 From: Jennyf19 Date: Sat, 23 Jan 2021 11:37:14 -0800 Subject: [PATCH 08/10] fix variable name --- ProjectTemplates/templates/Worker-CSharp/GreeterService.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ProjectTemplates/templates/Worker-CSharp/GreeterService.cs b/ProjectTemplates/templates/Worker-CSharp/GreeterService.cs index 1762ef204..3f55e2284 100644 --- a/ProjectTemplates/templates/Worker-CSharp/GreeterService.cs +++ b/ProjectTemplates/templates/Worker-CSharp/GreeterService.cs @@ -43,7 +43,7 @@ public GreeterService(ILogger logger, public override Task SayHello(HelloRequest request, ServerCallContext context) { var httpContext = context.GetHttpContext(); - httpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByAPI); + httpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi); using var response = await _downstreamWebApi.CallWebApiForUserAsync("DownstreamApi").ConfigureAwait(false); if (response.StatusCode == System.Net.HttpStatusCode.OK) { @@ -76,7 +76,7 @@ public GreeterService(ILogger logger, public override Task SayHello(HelloRequest request, ServerCallContext context) { var httpContext = context.GetHttpContext(); - httpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByAPI); + httpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi); var user = await _graphServiceClient.Me.Request().GetAsync(); return Task.FromResult(new HelloReply @@ -97,7 +97,7 @@ public override Task SayHello(HelloRequest request, ServerCallContex { #if (!NoAuth) var httpContext = context.GetHttpContext(); - httpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByAPI); + httpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi); #endif return Task.FromResult(new HelloReply { From df422caf694d949ab868cd834667172a25592d41 Mon Sep 17 00:00:00 2001 From: Jennyf19 Date: Mon, 25 Jan 2021 10:48:43 -0800 Subject: [PATCH 09/10] remove space --- ProjectTemplates/templates/Worker-CSharp/GreeterService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ProjectTemplates/templates/Worker-CSharp/GreeterService.cs b/ProjectTemplates/templates/Worker-CSharp/GreeterService.cs index 3f55e2284..2d856dc07 100644 --- a/ProjectTemplates/templates/Worker-CSharp/GreeterService.cs +++ b/ProjectTemplates/templates/Worker-CSharp/GreeterService.cs @@ -62,7 +62,7 @@ public override Task SayHello(HelloRequest request, ServerCallContex }); } -# elseif (GenerateGraph) +#elseif (GenerateGraph) private readonly GraphServiceClient _graphServiceClient; public GreeterService(ILogger logger, From ddf92fbfdbd9b43eb098840e75eddfaab415968a Mon Sep 17 00:00:00 2001 From: Jennyf19 Date: Mon, 25 Jan 2021 11:17:51 -0800 Subject: [PATCH 10/10] fix helloReply --- .../templates/Worker-CSharp/GreeterService.cs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/ProjectTemplates/templates/Worker-CSharp/GreeterService.cs b/ProjectTemplates/templates/Worker-CSharp/GreeterService.cs index 2d856dc07..4cc6a03a6 100644 --- a/ProjectTemplates/templates/Worker-CSharp/GreeterService.cs +++ b/ProjectTemplates/templates/Worker-CSharp/GreeterService.cs @@ -40,7 +40,7 @@ public GreeterService(ILogger logger, } [Authorize] - public override Task SayHello(HelloRequest request, ServerCallContext context) + public override async Task SayHello(HelloRequest request, ServerCallContext context) { var httpContext = context.GetHttpContext(); httpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi); @@ -56,10 +56,10 @@ public override Task SayHello(HelloRequest request, ServerCallContex throw new HttpRequestException($"Invalid status code in the HttpResponseMessage: {response.StatusCode}: {error}"); } - return Task.FromResult(new HelloReply + return new HelloReply() { Message = "Hello " + request.Name - }); + }; } #elseif (GenerateGraph) @@ -73,16 +73,16 @@ public GreeterService(ILogger logger, } [Authorize] - public override Task SayHello(HelloRequest request, ServerCallContext context) + public override async Task SayHello(HelloRequest request, ServerCallContext context) { var httpContext = context.GetHttpContext(); httpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi); var user = await _graphServiceClient.Me.Request().GetAsync(); - return Task.FromResult(new HelloReply + return new HelloReply() { - Message = "Hello " + user.Name - }); + Message = "Hello " + user.DisplayName + }; } #else public GreeterService(ILogger logger)