I have an application and I want to use a hybrid flow to call an API from my MVC web application. The API is secured and requires an access token (JWT). The code part on the API side is done. But how can I send my access token from my MVC application to the API in a service? I want to use a "generic" service for this that uses an httpclient.
I know that in controllers you can use
var accessToken = await HttpContext.GetTokenAsync("access_token");
or
var accessToken = await HttpContext.GetUserAccessTokenAsync();
But how can I access the access token in a service? Tried this too, but didn't work
var accessToken = _httpContextAccessor.HttpContext.Request.Headers[HeaderNames.Authorization];
Side question: how can I set the access token for the httpclient in the constructor of my service? (Using async methods is not possible) so I can't use this:
protected HttpClient HttpClient { get; private set; }
public MyGenericHttpClientService(IHttpContextAccessor httpContextAccessor)
{
var accessToken = await httpContextAccessor.HttpContext.GetTokenAsync("access_token");
HttpClient.SetBearerToken(accessToken);
}