[英]ASP.NET Core 2.0 Configuring Authentication with Services.Configure
[英]How properly configure authentication for consuming external Restful Apis in ASP.NET Core 2.0?
我正在使用外部Restful Api。 我提供了標題值的授權密鑰。 當我嘗試使用郵遞員發送請求時,返回200好的。我在代碼上使用相同的API KEY。 用授權密鑰消費Restful Api的正確方法是什么?
我已經為Startup.cs配置了ConfigureServices和Configure。 然后,我使用HttpClient來使用Restful Api。 我以某種方式收到401未經授權的回復。
Startup.cs的代碼
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy", builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});
services.AddAuthentication();
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseAuthentication();
app.UseCors("CorsPolicy");
app.UseMvc();
}
Services.cs的代碼:
private static HttpClient _httpClient = new HttpClient();
public CRUDService()
{
_httpClient.BaseAddress = new Uri("https://api.deezer.com");
_httpClient.DefaultRequestHeaders.Clear();
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("X-API_KEY", "081f0fca-1bca-4e8e-9a24-22ff2c3d462c");
_httpClient.Timeout = new TimeSpan(0, 0, 30);
_httpClient.DefaultRequestHeaders.Clear();
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
public async Task Run()
{
await GetResource();
}
public async Task GetResource()
{
var response = await _httpClient.GetAsync("/v1/song/latest");
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();
var movies = new List<Movie>();
if (response.Content.Headers.ContentType.MediaType == "application/json")
{
movies = JsonConvert.DeserializeObject<List<Movie>>(content);
}
}
我在該api上收到600個無效查詢,因此無法確認。 但是,我認為您需要像這樣添加api密鑰:
_httpClient.DefaultRequestHeaders.Add("X-API_KEY", "081f0fca-1bca-4e8e-9a24-22ff2c3d462c");
...而不是將其添加到DefaultRequestHeaders.Authorization。
保羅
我不確定它是否會正常工作,但是看起來好像沒有在實例化/初始化CRUDService-您可能需要執行以下操作:
public async Task GetResource()
{
CRUDService(); // <<<<---- this was added <<<<----
var response = await _httpClient.GetAsync("/v1/song/latest");
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();
var movies = new List<Movie>();
if (response.Content.Headers.ContentType.MediaType == "application/json")
{
movies = JsonConvert.DeserializeObject<List<Movie>>(content);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.