【问题标题】:How properly configure authentication for consuming external Restful Apis in ASP.NET Core 2.0?如何正确配置身份验证以在 ASP.NET Core 2.0 中使用外部 Restful API?
【发布时间】:2019-06-09 13:57:41
【问题描述】:

我正在使用外部 Restful Api。我为 headers 值提供了授权密钥。当我尝试使用邮递员发送请求时,它返回 200 Ok 我在代码上使用相同的 API KEY。使用授权密钥使用 Restful Api 的正确方法是什么?

我已经为 ConfigureServices 和 Configure 配置了 Startup.cs。然后我使用 HttpClient 来使用 Restful Api。不知何故,我收到了 401 Unauthorized 响应。

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 密钥...
  • @MattOestreich 是的,没错。出于安全目的。对不起。您知道如何在 Startup.cs 中全局注册该 API 密钥,以便它可以通过应用程序访问吗?谢谢
  • 您将使用 app.config/web.config 文件:stackoverflow.com/questions/5989736/…
  • ASP.NET Core 有一个完整的configuration 系统供 where 存储诸如 API 密钥之类的东西。 environment variable 可能是生产工作流的好地方(如果你在 Azure 中,Azure Key Vault)。
  • 我建议通读Initiate HTTP requests,以了解如何有效地使用HttpClient

标签: c# asp.net-core-webapi asp.net-core-2.1


【解决方案1】:

我在该 api 上收到 600 个无效查询,所以我无法确认。但是,我认为您需要像这样添加 api 密钥:

_httpClient.DefaultRequestHeaders.Add("X-API_KEY", "081f0fca-1bca-4e8e-9a24-22ff2c3d462c");

...而不是将其添加到 DefaultRequestHeaders.Authorization。

保罗

【讨论】:

    【解决方案2】:

    我不确定它是否会起作用,但看起来您不是在实例化/初始化 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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-08-15
      • 1970-01-01
      • 2018-06-16
      • 1970-01-01
      • 1970-01-01
      • 2018-01-28
      • 2018-03-30
      • 2018-03-09
      • 2011-10-02
      相关资源
      最近更新 更多