ASP.NET Core 5 Web API在用户未经身份验证时返回404代码而非401

6

我有一个基于ASP.NET 5框架编写的Web API,其中包含Swagger UI。

当用户对任何端点进行身份验证请求时,我会收到404错误,“就好像框架将用户重定向到不存在的页面一样!”如果框架自动重定向请求由于未经授权的请求,我希望更改该行为,以便返回401 json响应。如果不是这样,我该如何将响应代码从404更改为401作为JSON响应?

以下是Startup类的外观

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();

    services.AddSwaggerGen(swagger =>
    {
        swagger.SwaggerDoc("v1", new OpenApiInfo
        {
            Version = "v1",
            Title = "Student Athlete Wellness Tracker API",
            Description = "API to provide data for the Student Athlete Wellness Trackers",

        });
        swagger.AddSecurityDefinition("basic", new OpenApiSecurityScheme()
        {
            Name = "Authorization",
            Type = SecuritySchemeType.Http,
            Scheme = "basic",
            In = ParameterLocation.Header,
            Description = "Basic Authorization header using the Bearer scheme.",
        });

        swagger.AddSecurityRequirement(new OpenApiSecurityRequirement
        {
            {
                new OpenApiSecurityScheme
                {
                    Reference = new OpenApiReference
                    {
                        Type = ReferenceType.SecurityScheme,
                        Id = "basic"
                    }
                },
                Array.Empty<string>()
            }
        });
    });

    services.AddAuthentication("BasicAuthentication")
            .AddScheme<AuthenticationSchemeOptions, BasicAuthenticationHandler>("BasicAuthentication", null);
}


public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/error");
        app.UseHsts();
    }
    app.UseSwagger();
    app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Student Athlete Wellness Trackers - v1"));

    app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

    app.UseHttpsRedirection();

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

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}
2个回答

5

1
为了解决这个问题,我进行了更改。
services.AddAuthentication("BasicAuthentication")
        .AddScheme<AuthenticationSchemeOptions, BasicAuthenticationHandler>("BasicAuthentication", null);

services.AddAuthentication(opts =>
{
    opts.DefaultAuthenticateScheme = "BasicAuthentication";
    opts.DefaultChallengeScheme = "BasicAuthentication";
    opts.DefaultScheme = "BasicAuthentication";
    opts.AddScheme<BasicAuthenticationHandler>("BasicAuthentication", null);
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接