I'm writing an Asp.Net Core 2.2 application in which I'm adding HttpClient.
services.AddAuthentication(o => {
o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
o.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
o.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddQuickbooksOnline(o => {
o.ClientId = Configuration["ecm.qbo.client-id"];
o.ClientSecret = Configuration["ecm.qbo.client-secret"];
o.Scope.Add(QuickbooksOnlineScopes.Accounting);
});
services.AddHttpClient("qbo", c => {
c.BaseAddress = new Uri("https://sandbox-quickbooks.api.intuit.com");
c.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
c.DefaultRequestHeaders.Add("content-type", "application/json");
c.DefaultRequestHeaders.Authorization=// How do I get the token to be assigned here?
});
service.AddScoped<IInventoryService, QboInventoryService>();
So, basically I wrote myself an extension which allows me to AddQuickbooksOnline authentication using minimal configuration as many configurations is made by default by the extension.
Once registered and authenticated to my app, I display a GetProducts button to the authenticated user.
I want this button to call upon my ProductController.
public class ProductController : ControllerBase {
private readonly IInventoryService _inventoryService;
public ProductController(IInventoryService inventoryService) {
_inventoryService=inventoryService??throw new ArgumentNullException(nameof(inventoryService));
}
public async Task<IEnumerable<Product>> Get() {
var products=await _inventoryService.GetAllProducts();
return products;
}
}
And the service actually depends on the configured HttpClient I want to add in my services configuration.
public class QboInventoryService : IInventoryService {
private readonly IHttpClientFactory _clientFactory;
private readonly IConfiguration _config;
public QboInventoryService(IHttpClientFactory clientFactory, IConfiguration config) {
_clientFactory=clientFactory??throw new ArgumentNullException(nameof(clientFactory));
_config=config??throw new ArgumentNullException(nameof(config));
}
public async Task<IEnumerable<Product>> GetAllProducts() {
IEnumerable<Product> products=new List<Product>();
var client=_clientFactory.CreateClient("qbo");
var response=await client.GetAsync(config["qbo.products.query"]);
if(response.IsSuccessStatusCode) {
var content=await response.Content.ReadAsStringAsync();
products=JsonConvert.DeserializeObject<IEnumerable<Product>>(content);
}
return products;
}
}
So, in order to make my call to the QBO WebAPI, I need to provide the OAuth token of authenticated user to the HttpClient being instantiated.