大约6个月前,我推出了一个网站,每个请求都需要通过https。当时我能找到的确保每个页面请求都是通过https的唯一方法是在页面加载事件中检查它。如果请求不是通过http,我会response.redirect("https://example.com")

有没有更好的方法,比如web。config中的一些设置?


当前回答

I'm going to throw my two cents in. IF you have access to IIS server side, then you can force HTTPS by use of the protocol bindings. For example, you have a website called Blah. In IIS you'd setup two sites: Blah, and Blah (Redirect). For Blah only configure the HTTPS binding (and FTP if you need to, make sure to force it over a secure connection as well). For Blah (Redirect) only configure the HTTP binding. Lastly, in the HTTP Redirect section for Blah (Redirect) make sure to set a 301 redirect to https://blah.com, with exact destination enabled. Make sure that each site in IIS is pointing to it's own root folder otherwise the Web.config will get all screwed up. Also make sure to have HSTS configured on your HTTPSed site so that subsequent requests by the browser are always forced to HTTPS and no redirects occur.

其他回答

我花了一些时间寻找有意义的最佳实践,发现下面的方法非常适合我。我希望这能帮你节省时间。

使用配置文件(例如asp.net网站) https://blogs.msdn.microsoft.com/kaushal/2013/05/22/http-to-https-redirects-on-iis-7-x-and-higher/

或者在你自己的服务器上 https://www.sslshopper.com/iis7-redirect-http-to-https.html

(简答) 下面的代码放在里面

<system.webServer> 
 <rewrite>
     <rules>
       <rule name="HTTP/S to HTTPS Redirect" enabled="true" 
           stopProcessing="true">
       <match url="(.*)" />
        <conditions logicalGrouping="MatchAny">
        <add input="{SERVER_PORT_SECURE}" pattern="^0$" />
       </conditions>
       <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" 
        redirectType="Permanent" />
        </rule>
       </rules>
 </rewrite>

您还可以通过向浏览器返回“Strict-Transport-Security”报头来使用HSTS。浏览器必须支持这一点(目前主要是Chrome和Firefox支持),但这意味着一旦设置好,浏览器将不会通过HTTP向站点发出请求,而是在发出请求之前将它们转换为HTTPS请求。尝试结合从HTTP重定向:

protected void Application_BeginRequest(Object sender, EventArgs e)
{
  switch (Request.Url.Scheme)
  {
    case "https":
      Response.AddHeader("Strict-Transport-Security", "max-age=300");
      break;
    case "http":
      var path = "https://" + Request.Url.Host + Request.Url.PathAndQuery;
      Response.Status = "301 Moved Permanently";
      Response.AddHeader("Location", path);
      break;
  }
}

不了解HSTS的浏览器将忽略头文件,但仍然会被switch语句捕获并发送到HTTPS。

I'm going to throw my two cents in. IF you have access to IIS server side, then you can force HTTPS by use of the protocol bindings. For example, you have a website called Blah. In IIS you'd setup two sites: Blah, and Blah (Redirect). For Blah only configure the HTTPS binding (and FTP if you need to, make sure to force it over a secure connection as well). For Blah (Redirect) only configure the HTTP binding. Lastly, in the HTTP Redirect section for Blah (Redirect) make sure to set a 301 redirect to https://blah.com, with exact destination enabled. Make sure that each site in IIS is pointing to it's own root folder otherwise the Web.config will get all screwed up. Also make sure to have HSTS configured on your HTTPSed site so that subsequent requests by the browser are always forced to HTTPS and no redirects occur.

对于那些使用ASP。净MVC。您可以使用以下两种方式在整个站点上强制使用HTTPS之上的SSL/TLS:

艰难的方式

1 -添加requirehttpattribute到全局过滤器:

GlobalFilters.Filters.Add(new RequireHttpsAttribute());

2 -强制防伪造令牌使用SSL/TLS:

AntiForgeryConfig.RequireSsl = true;

3 -通过更改Web,要求cookie默认要求HTTPS。配置文件:

<system.web>
    <httpCookies httpOnlyCookies="true" requireSSL="true" />
</system.web>

4 -使用NWebSec。拥有NuGet包并添加以下代码行以启用整个站点的严格传输安全。不要忘记在下面添加Preload指令,并将您的网站提交到HSTS Preload站点。更多信息在这里和这里。请注意,如果您不使用OWIN,也可以使用Web。config方法,你可以在NWebSec网站上阅读。

// app is your OWIN IAppBuilder app in Startup.cs
app.UseHsts(options => options.MaxAge(days: 30).Preload());

5 -使用NWebSec。拥有NuGet包并添加以下代码行,以启用跨站点的公钥固定(HPKP)。更多信息在这里和这里。

// app is your OWIN IAppBuilder app in Startup.cs
app.UseHpkp(options => options
    .Sha256Pins(
        "Base64 encoded SHA-256 hash of your first certificate e.g. cUPcTAZWKaASuYWhhneDttWpY3oBAkE3h2+soZS7sWs=",
        "Base64 encoded SHA-256 hash of your second backup certificate e.g. M8HztCzM3elUxkcjR2S5P4hhyBNf6lHkmjAHKhpGPWE=")
    .MaxAge(days: 30));

6 -包括https方案在任何URL的使用。当您在某些浏览器中限制该方案时,内容安全策略(CSP) HTTP报头和子资源完整性(SRI)不能很好地发挥作用。对于HTTPS最好是明确的。如。

<script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.4/bootstrap.min.js"></script>

简单的方法

使用ASP。NET MVC样板Visual Studio项目模板生成一个项目,所有这些和更多的内置。你也可以在GitHub上查看代码。

对于上面的@Joe,“这是给我一个重定向循环。在我添加代码之前,它工作得很好。有什么建议吗?——乔11月8日11月4点13分

这种情况也发生在我身上,我认为发生的情况是有一个负载均衡器在Web服务器前终止SSL请求。因此,我的Web站点总是认为请求是“http”,即使原始浏览器要求它是“https”。

I admit this is a bit hacky, but what worked for me was to implement a "JustRedirected" property that I could leverage to figure out the person was already redirected once. So, I test for specific conditions that warrant the redirect and, if they are met, I set this property (value stored in session) prior to the redirection. Even if the http/https conditions for redirection are met the second time, I bypass the redirection logic and reset the "JustRedirected" session value to false. You'll need your own conditional test logic, but here's a simple implementation of the property:

    public bool JustRedirected
    {
        get
        {
            if (Session[RosadaConst.JUSTREDIRECTED] == null)
                return false;

            return (bool)Session[RosadaConst.JUSTREDIRECTED];
        }
        set
        {
            Session[RosadaConst.JUSTREDIRECTED] = value;
        }
    }