diff --git a/tests/DevApps/GenericWebApi/Controllers/AuthorizationHeader.cs b/tests/DevApps/GenericWebApi/Controllers/AuthorizationHeader.cs new file mode 100644 index 000000000..4b374c343 --- /dev/null +++ b/tests/DevApps/GenericWebApi/Controllers/AuthorizationHeader.cs @@ -0,0 +1,52 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Identity.Abstractions; +using Microsoft.Identity.Web.Resource; + +namespace webApi.Controllers; + +[Authorize] +[ApiController] +[Route("[controller]")] +[RequiredScope(RequiredScopesConfigurationKey = "AzureAd:Scopes")] +public class AuthorizationHeader : ControllerBase +{ + private readonly ILogger _logger; + + private readonly IAuthorizationHeaderProvider _authorizationHeaderProvider; + + private readonly IConfiguration _configuration; + + public AuthorizationHeader(ILogger logger, + IAuthorizationHeaderProvider authorizationHeaderProvider, + IConfiguration configuration) + { + _logger = logger; + _authorizationHeaderProvider = authorizationHeaderProvider; + _configuration = configuration; + } + + + [HttpGet(Name = "GetAuthorizationHeader")] + public async Task GetAuthorizationHeader(string serviceName) + { + Dictionary downstreamApiOptions = new Dictionary(); + _configuration.GetSection("DownstreamApis").Bind(downstreamApiOptions); + + if (!downstreamApiOptions.ContainsKey(serviceName)) + { + throw new ArgumentException($"The downstream API {serviceName} is not configured."); + } + + var serviceOptions = downstreamApiOptions[serviceName]; + if (serviceOptions.RequestAppToken) + { + return await _authorizationHeaderProvider.CreateAuthorizationHeaderForAppAsync(serviceOptions.Scopes?.FirstOrDefault()!, serviceOptions); + } + else + { + return await _authorizationHeaderProvider.CreateAuthorizationHeaderForUserAsync(serviceOptions.Scopes!, serviceOptions); + } + } + +} diff --git a/tests/DevApps/GenericWebApi/Controllers/DownstreamApi.cs b/tests/DevApps/GenericWebApi/Controllers/DownstreamApi.cs new file mode 100644 index 000000000..afc9d5046 --- /dev/null +++ b/tests/DevApps/GenericWebApi/Controllers/DownstreamApi.cs @@ -0,0 +1,48 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Identity.Abstractions; +using Microsoft.Identity.Web.Resource; + +namespace webApi.Controllers; + +[Authorize] +[ApiController] +[Route("[controller]")] +[RequiredScope(RequiredScopesConfigurationKey = "AzureAd:Scopes")] +public class DownstreamApi : ControllerBase +{ + private readonly ILogger _logger; + + private readonly IDownstreamApi _downstreamApi; + + public DownstreamApi(ILogger logger, + IDownstreamApi downstreamApi) + { + _logger = logger; + _downstreamApi = downstreamApi; + } + + /// + /// Call downstream API + /// + /// Name of the service to call. This is the name of the downstream API + /// options in the appsettings.json file. + /// + /// + /// + [HttpGet(Name = "CallDownstreamWebApi")] + public async Task CallDownstreamWebApi(string serviceName, string input) + { + using var response = await _downstreamApi.CallApiAsync(serviceName, content:new StringContent(input)).ConfigureAwait(false); + if (response.StatusCode == System.Net.HttpStatusCode.OK) + { + var apiResult = await response.Content.ReadAsStringAsync().ConfigureAwait(false); + return apiResult; + } + else + { + var error = await response.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new HttpRequestException($"Invalid status code in the HttpResponseMessage: {response.StatusCode}: {error}"); + } + } +} diff --git a/tests/DevApps/GenericWebApi/Program.cs b/tests/DevApps/GenericWebApi/Program.cs new file mode 100644 index 000000000..7090a5d63 --- /dev/null +++ b/tests/DevApps/GenericWebApi/Program.cs @@ -0,0 +1,44 @@ +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.Identity.Abstractions; +using Microsoft.Identity.Web; +using Microsoft.Identity.Web.TokenCacheProviders.InMemory; + +var builder = WebApplication.CreateBuilder(args); + +// Add services to the container. +builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) + .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd")); + +// Enable the token acquisition +builder.Services.AddTokenAcquisition(); +builder.Services.AddInMemoryTokenCaches(); + +// Read the web APIs from the appsettings.json +Dictionary downstreamApiOptions = new Dictionary(); +builder.Configuration.GetSection("DownstreamApis").Bind(downstreamApiOptions); +foreach (var options in downstreamApiOptions) +{ + builder.Services.AddDownstreamApi(options.Key, builder.Configuration.GetSection($"DownstreamApis:{options.Key}")); +} + +builder.Services.AddControllers(); +// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle +builder.Services.AddEndpointsApiExplorer(); +builder.Services.AddSwaggerGen(); + +var app = builder.Build(); + +// Configure the HTTP request pipeline. +if (app.Environment.IsDevelopment()) +{ + app.UseSwagger(); + app.UseSwaggerUI(); +} + +app.UseHttpsRedirection(); + +app.UseAuthorization(); + +app.MapControllers(); + +app.Run(); diff --git a/tests/DevApps/GenericWebApi/Properties/launchSettings.json b/tests/DevApps/GenericWebApi/Properties/launchSettings.json new file mode 100644 index 000000000..bdd44762a --- /dev/null +++ b/tests/DevApps/GenericWebApi/Properties/launchSettings.json @@ -0,0 +1,31 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:61886", + "sslPort": 44318 + } + }, + "profiles": { + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "https://localhost:7156;http://localhost:5280", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/tests/DevApps/GenericWebApi/WeatherForecast.cs b/tests/DevApps/GenericWebApi/WeatherForecast.cs new file mode 100644 index 000000000..5b3d7e335 --- /dev/null +++ b/tests/DevApps/GenericWebApi/WeatherForecast.cs @@ -0,0 +1,12 @@ +namespace webApi; + +public class WeatherForecast +{ + public DateOnly Date { get; set; } + + public int TemperatureC { get; set; } + + public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); + + public string? Summary { get; set; } +} diff --git a/tests/DevApps/GenericWebApi/appsettings.Development.json b/tests/DevApps/GenericWebApi/appsettings.Development.json new file mode 100644 index 000000000..0c208ae91 --- /dev/null +++ b/tests/DevApps/GenericWebApi/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/tests/DevApps/GenericWebApi/appsettings.json b/tests/DevApps/GenericWebApi/appsettings.json new file mode 100644 index 000000000..156072b78 --- /dev/null +++ b/tests/DevApps/GenericWebApi/appsettings.json @@ -0,0 +1,38 @@ +{ + /* +The following identity settings need to be configured +before the project can be successfully executed. +For more info see https://aka.ms/dotnet-template-ms-identity-platform +*/ + "AzureAd": { + "Instance": "https://login.microsoftonline.com/", + "Domain": "qualified.domain.name", + "TenantId": "22222222-2222-2222-2222-222222222222", + "ClientId": "11111111-1111-1111-11111111111111111", + + "ClientSecret": "secret-from-app-registration", + "ClientCertificates": [ + ], + "Scopes": "access_as_user", + "CallbackPath": "/signin-oidc" + }, + + "DownstreamApis": { + "Api1": { + "BaseUrl": "URL", + "Scopes": "SCOPES" + }, + "Api2": { + "BaseUrl": "https://graph.microsoft.com/v1.0", + "Scopes": "user.read" + } + }, + + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/tests/DevApps/GenericWebApi/webApi.csproj b/tests/DevApps/GenericWebApi/webApi.csproj new file mode 100644 index 000000000..e52a18b15 --- /dev/null +++ b/tests/DevApps/GenericWebApi/webApi.csproj @@ -0,0 +1,17 @@ + + + + net7.0 + enable + enable + aspnet-webApi-9251618e-8831-4703-8007-ef5a00a2f0b4 + + + + + + + + + + diff --git a/tests/DevApps/GenericWebApi/webApi.sln b/tests/DevApps/GenericWebApi/webApi.sln new file mode 100644 index 000000000..7f96a5b01 --- /dev/null +++ b/tests/DevApps/GenericWebApi/webApi.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.5.33530.505 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "webApi", "webApi.csproj", "{C2B3CAAB-91ED-45D4-805E-71C1149D5B7B}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {C2B3CAAB-91ED-45D4-805E-71C1149D5B7B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C2B3CAAB-91ED-45D4-805E-71C1149D5B7B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C2B3CAAB-91ED-45D4-805E-71C1149D5B7B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C2B3CAAB-91ED-45D4-805E-71C1149D5B7B}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {A3F56DE1-3327-4453-AA80-A0714CAF71CA} + EndGlobalSection +EndGlobal