-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
41 lines (36 loc) · 1.87 KB
/
Program.cs
File metadata and controls
41 lines (36 loc) · 1.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
using System.Text.Json;
// <ms_docref_import_types>
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Identity.Web;
// </ms_docref_import_types>
// <ms_docref_add_msal>
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
// Acquire an access token from Microsoft Entra ID for this client to access Microsoft Graph based
// on the permissions granted this application in its Microsoft Entra App registration.
// The client credential flow will automatically attempt to use or renew any cached
// tokens, without the need to call acquireTokenSilently first.
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"))
.EnableTokenAcquisitionToCallDownstreamApi()
.AddInMemoryTokenCaches()
.AddDownstreamWebApi("GraphApi", builder.Configuration.GetSection("GraphApi"));
// </ms_docref_add_msal>
WebApplication app = builder.Build();
// <ms_docref_protect_endpoint>
app.MapGet("api/application", async (IDownstreamWebApi downstreamWebApi) =>
{
using var response = await downstreamWebApi.CallWebApiForAppAsync("GraphApi").ConfigureAwait(false);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
var graphApiResponse = await response.Content.ReadFromJsonAsync<JsonDocument>().ConfigureAwait(false);
return JsonSerializer.Serialize(graphApiResponse, new JsonSerializerOptions { WriteIndented = true });
}
else
{
var error = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
throw new HttpRequestException($"Invalid status code in the HttpResponseMessage: {response.StatusCode}: {error}");
}
});
// </ms_docref_protect_endpoint>
app.Run();