We’re developing an aspnet core website with webapi backend all on a cloud platform. The auth part is implemented with openidconnect and cookies. Every tab is a new application to reduce release and test times. For the website / applications we have a razor class library that contains the main layout. See all posts in this series cloudnative
To call an upstream api from the website we need a token. This was added to the cookie in Fix HTTP431 Request header fields too large. Now we can get the token with GetTokenAsync, configure the client and inject the client into our adapter.
using RestSharp; // see https://restsharp.dev
builder.Services.AddScoped<IRestClient>(options =>
{
var environment = options.GetRequiredService<IConfiguration>();
var url = environment.GetValue<string>("url")!;
var client = new RestClient(url);
// make sure token is saved
var context = options.GetRequiredService<IHttpContextAccessor>();
var token = context.HttpContext!.GetTokenAsync("access_token").Result;
client.AddDefaultHeader("Authorization", $"Bearer {token}");
return client;
});
Pingback: Call upstream api with token from jQuery | .NET Development by Eric