【问题标题】:Fresh .net web api solution return 401 for WeatherForecastController新鲜的 .net web api 解决方案为 WeatherForecastController 返回 401
【发布时间】:2021-06-20 12:43:39
【问题描述】:

我使用身份用户 (IdentityServer) 安装了一个全新的 .net 核心 Web api (5.0)。 我添加了一个中间件:

public class ApiKeyMiddleware
{
    private readonly RequestDelegate _next;
    private const string APIKEYNAME = "ApiKey";
    public ApiKeyMiddleware(RequestDelegate next)
    {
        _next = next;
    }
    public async Task InvokeAsync(HttpContext context)
    {
        if (!context.Request.Headers.TryGetValue(APIKEYNAME, out var extractedApiKey))
        {
            context.Response.StatusCode = 401;
            await context.Response.WriteAsync("Api Key was not provided. (Using ApiKeyMiddleware) ");
            return;
        }

        var appSettings = context.RequestServices.GetRequiredService<IConfiguration>();

        var apiKey = appSettings.GetValue<string>(APIKEYNAME);

        if (!apiKey.Equals(extractedApiKey))
        {
            context.Response.StatusCode = 401;
            await context.Response.WriteAsync("Unauthorized client. (Using ApiKeyMiddleware)");
            return;
        }

        await _next(context);
    }
}

在我的启动中,我添加了一个中间件组件:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        //services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        //    .AddMicrosoftIdentityWebApi(Configuration.GetSection("AzureAd"));

        services.AddControllers();
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo { Title = "Test002.Api", Version = "v1" });
        });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseSwagger();
            app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Test002.Api v1"));
        }

        app.UseHttpsRedirection();
        app.UseMiddleware<ApiKeyMiddleware>();
        app.UseRouting();

        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

当我打开 swagger 配置时,我得到 401:未经授权。 我错过了什么?

这是我 gdrive 上解决方案的 link。

【问题讨论】:

    标签: c# api .net-core asp.net-core-webapi identityserver4


    【解决方案1】:

    当请求标头不包含ApiKey,或者它与 appsettings.json 中的不匹配时,您已将响应 StatusCode 设置为 401。当你用swagger测试时,它不会在请求头中添加ApiKey。

    【讨论】:

    • 如何编辑当我调用 api 实际添加 apiKey 时的招摇?我实际上需要将不记名令牌传递给我的 api 调用并从我的 api 方法获得响应
    猜你喜欢
    • 2020-12-08
    • 2015-08-26
    • 2018-10-06
    • 1970-01-01
    • 2020-01-19
    • 1970-01-01
    • 2018-03-05
    • 2020-05-05
    • 1970-01-01
    相关资源
    最近更新 更多