C# 使用api密钥限制Swagger.net core中的某些端点

C# 使用api密钥限制Swagger.net core中的某些端点,c#,api,swagger,C#,Api,Swagger,我有一个NetCore2.2项目和apicontrollers,EF,我使用最新的虚张声势的NetCore4.0.1 它的设置,一切都在工作,它在swagger中显示了来自控制器的所有api端点 问题是:我们希望通过在请求头中使用api密钥来保护此api。我们希望用户A只在usercontroller中使用例如/GetAllUsers,但用户B可以在usercontroller中看到所有api端点 我还没有找到这样的例子 这是我的想法。 场景一:用户A进入api地址并得到提示输入用户名和密码(密

我有一个NetCore2.2项目和apicontrollers,EF,我使用最新的虚张声势的NetCore4.0.1

它的设置,一切都在工作,它在swagger中显示了来自控制器的所有api端点

问题是:我们希望通过在请求头中使用api密钥来保护此api。我们希望用户A只在usercontroller中使用例如/GetAllUsers,但用户B可以在usercontroller中看到所有api端点

我还没有找到这样的例子

这是我的想法。 场景一:用户A进入api地址并得到提示输入用户名和密码(密码为apikey),我们检查数据库是否有匹配的用户名和密码。如果是这样,我们将用户定向到该用户有权访问的招摇过市视图/端点

场景二:发送报头中的apikey,我们检查数据库并返回正确的视图

这可行吗

这就是我的启动看起来的样子,这是一个用于swagger/startup的扩展方法,我在其中配置了它

启动:

public void ConfigureServices(IServiceCollection services)
{
 services.AddUnitOfWork();
 services.AddHelpers();

 services.AddTransient(typeof(IPipelineBehavior<,>), 
 typeof(RequestValidationBehavior<,>));
 services.AddMediatR();
 services.AddConfiguredSwagger(); // <--- extension
 services.AddMvc()
 .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

// This method gets called by the runtime. Use this method to configure 
the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();

 // Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
}


// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), 
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", 
typeof(Startup).Namespace);
options.RoutePrefix = string.Empty;
});

app.UseMvc();

app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello");
});
}
public static class SwaggerServiceCollectionExtensions
{
public static IServiceCollection AddConfiguredSwagger(this 
IServiceCollection services)
{
    // Register the Swagger generator, defining 1 or more Swagger documents
    return services.AddSwaggerGen(options =>
    {
        options.SwaggerDoc("v1", new Info { Title = 
        typeof(Startup).Namespace, Version = "v1" });
        var xmlFile = $" 
    {Assembly.GetExecutingAssembly().GetName().Name}.xml";
        var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);

        options.IncludeXmlComments(xmlPath);
    });
 }
}