在Swagger index.html中添加HSTS头

c86crjj0  于 5个月前  发布在  其他
关注(0)|答案(1)|浏览(72)

我们的Rest API是笔测试,HSTS错误只在swagger生成的index.html上返回。
它是一个.net core 6 REST API,端点都返回一个有效的响应,它只在swagger生成的index.html上。
在我的program.cs中,我有以下设置:

internal static void SetupSecurity(this IServiceCollection services)
    {
        SecurityConfiguration securityConfiguration = services
            .BuildServiceProvider()
            .GetConfigurationData<SecurityConfiguration>();

        if (securityConfiguration.UseSSL)
        {
            services
                .AddHsts(options =>
                {
                    options.IncludeSubDomains = true;
                    options.MaxAge = TimeSpan.FromDays(securityConfiguration.MaxAge);
                })
                .AddHttpsRedirection(options =>
                {
                    options.RedirectStatusCode = (int)HttpStatusCode.TemporaryRedirect;
                    options.HttpsPort = securityConfiguration.HttpsPort;
                });
        }
    }

字符串
在我的program.cs中,这是通过做services.SetupSecrity ad app.SetupSecurity调用的,但这只适用于端点,而不是swagger html(这是有道理的)。
有没有其他人遇到过这种情况,如果有,什么是最好的解决方案?我似乎找不到任何地方可以让我注入html页面swagger生成添加相关的响应头。
我不能只是在IIS中添加它,因为端点返回多个头,这似乎是不正确的。我可以从代码中完全删除它,但这将导致大量的技术支持,以更新客户的安装。

x759pob2

x759pob21#

问题中的代码显示了如何配置和注册必要的服务,在ASP.NET管道中应用这些服务的顺序才是关键。
在调用UseSwaggerUI之前,请确保已调用app.UseHsts()
从文档
添加用于使用HSTS的中间件,该中间件添加了HSTS-Transport-Security标头。

if (!env.IsDevelopment())
{
    app.UseHsts();
}

app.UseHttpsRedirection();

// ....

app.UseSwagger();
app.UseSwaggerUI();

// ...

字符串

相关问题