Call upstream api with token

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;
});

About erictummers

Working in a DevOps team is the best thing that happened to me. I like challenges and sharing the solutions with others. On my blog I’ll mostly post about my work, but expect an occasional home project, productivity tip and tooling review.
This entry was posted in Development and tagged . Bookmark the permalink.

1 Response to Call upstream api with token

  1. Pingback: Call upstream api with token from jQuery | .NET Development by Eric

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.