c# - 如何在 ASP.Net Core 6.0 中实现 HSTS header ?

标签 c# asp.net asp.net-core asp.net-core-6.0 hsts

我需要在 ASP.Net Core 6.0 WEB API 应用程序中实现 HSTS header 安全性。

下面是我的Program.cs

    var builder = WebApplication.CreateBuilder(args);
    ...
    // Https redirection
    builder.Services.AddHttpsRedirection(options =>
    {
        options.RedirectStatusCode = (int)HttpStatusCode.TemporaryRedirect;
        options.HttpsPort = 7075;
    });
    
    // HSTS Security Headers 
    builder.Services.AddHsts(options =>
    {
        options.Preload = true;
        options.IncludeSubDomains = true;
        options.MaxAge = TimeSpan.FromDays(365);
    });
    
    var app = builder.Build();
    
    // Configure the HTTP request pipeline.
    if (app.Environment.IsDevelopment())
    {
        app.UseSwagger();
        app.UseSwaggerUI();
        app.UseHsts();
    }
    
    app.UseHttpsRedirection();
    
    app.UseAuthorization();
    
    app.UseCustomExceptionHandler();
    
    app.MapControllers();
    
    app.Run();

下面是launchSettings.json

{
  "$schema": "https://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:17240",
      "sslPort": 0
    }
  },
  "profiles": {
    "EFCoreRelationshipsTutorial": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "launchUrl": "swagger",
      "applicationUrl": "http://localhost:5075;https://localhost:7075",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "swagger",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

应用程序在 URL 上启动 - http://localhost:5075/swagger/index.html 但是,我期望它会自动重定向到 https://localhost:7075/swagger/index.html。

此外,我期待像这样的响应中的严格传输安全 header

enter image description here

但是,它不存在于响应 header 中。

enter image description here

我错过了什么?如何在 asp.net core 6.0 中实现 HSTS?

最佳答案

.AddHsts() 排除了 localhost 这就是为什么您看不到它在您的开发机器上工作的原因;以及为什么只建议在生产中使用它。

来自 asp.net 文档 HTTP Strict Transport Security Protocol (HSTS) :

UseHsts isn't recommended in development because the HSTS settings are highly cacheable by browsers. By default, UseHsts excludes the local loopback address.

For production environments that are implementing HTTPS for the first time, set the initial HstsOptions.MaxAge to a small value using one of the TimeSpan methods. Set the value from hours to no more than a single day in case you need to revert the HTTPS infrastructure to HTTP. After you're confident in the sustainability of the HTTPS configuration, increase the HSTS max-age value; a commonly used value is one year.

然后是一段代码:

using System.Net;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRazorPages();

builder.Services.AddHsts(options =>
{
    options.Preload = true;
    options.IncludeSubDomains = true;
    options.MaxAge = TimeSpan.FromDays(60);
    options.ExcludedHosts.Add("example.com");
    options.ExcludedHosts.Add("www.example.com");
});

builder.Services.AddHttpsRedirection(options =>
{
    options.RedirectStatusCode = (int)HttpStatusCode.TemporaryRedirect;
    options.HttpsPort = 5001;
});

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapRazorPages();

app.Run();

本文的其余部分更详细地解释了配置选项和行为。

编辑:在本地测试 UseHsts

只是做了一些实验,通过在我的 Windows 主机文件中创建一个条目并更新我的 launchSettings,能够将 Strict-Transport-Security header 添加到 Postman 请求中。 json.

编辑你的主机文件; example on SuperUser .

文件:C:\Windows\System32\drivers\etc\hosts

添加一些内容:

127.0.0.1 myweb.local

保存文件(您可能需要在管理员模式下打开您的编辑器)。并使用您发布的设置,将主机名从本地主机修改为主机文件中定义的站点名称,即 myweb.local

"profiles": {
    "EFCoreRelationshipsTutorial": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "launchUrl": "swagger",
      "applicationUrl": "http://myweb.local:5075;https://myweb.local:7075",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
}

当然,我的环境只启用了 https,但在主机文件中创建条目并更新我的启动设置以使用我映射回 127.0.0.1 的主机名后, header 出现了。

关于c# - 如何在 ASP.Net Core 6.0 中实现 HSTS header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73376095/

相关文章:

c# - 每次使用 Serilog 创建新记录器时,都会创建一个具有更新后缀的新文件

c# - 如何将项目位置限制在 Canvas 中?

c# - 如何获取上传进度?

c# - 如何使用 OOP 进行设计

javascript - FineUploader 构造函数失败

c# - 如何在传递接口(interface)时访问不同具体类的属性

c# - 使用 Redis ServiceStack 的事务时如何创建多个序列号

css - 在 GridView (ASP.NET) 中卡住/固定 header

javascript - 如何使用 React 应用程序将 ASP.NET Core Controller 操作 View 之一访问到 iframe 中?

asp.net-core - 如何从 ASP.Net Core 中的日志条目中删除属性