我正在编写一个 Asp.Net Core 2.2 应用程序,我在其中添加了 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>();
所以,基本上我给自己写了一个扩展,它允许我使用最少的配置进行 AddQuickbooksOnline 身份验证,因为扩展默认会进行许多配置。
在我的应用程序注册并通过身份验证后,我会向经过身份验证的用户显示一个 GetProducts 按钮。
我希望这个按钮调用我的 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;
}
}
并且该服务实际上取决于我要在我的服务配置中添加的已配置 HttpClient。
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;
}
}
因此,为了调用 QBO WebAPI,我需要将经过身份验证的用户的 OAuth 令牌提供给正在实例化的 HttpClient。