大约6个月前,我推出了一个网站,每个请求都需要通过https。当时我能找到的确保每个页面请求都是通过https的唯一方法是在页面加载事件中检查它。如果请求不是通过http,我会response.redirect("https://example.com")
有没有更好的方法,比如web。config中的一些设置?
大约6个月前,我推出了一个网站,每个请求都需要通过https。当时我能找到的确保每个页面请求都是通过https的唯一方法是在页面加载事件中检查它。如果请求不是通过http,我会response.redirect("https://example.com")
有没有更好的方法,比如web。config中的一些设置?
当前回答
我花了一些时间寻找有意义的最佳实践,发现下面的方法非常适合我。我希望这能帮你节省时间。
使用配置文件(例如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>
其他回答
请使用HSTS (HTTP严格传输安全)
从http://www.hanselman.com/blog/HowToEnableHTTPStrictTransportSecurityHSTSInIIS7.aspx
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="HTTP to HTTPS redirect" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{HTTPS}" pattern="off" ignoreCase="true" />
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}/{R:1}"
redirectType="Permanent" />
</rule>
</rules>
<outboundRules>
<rule name="Add Strict-Transport-Security when HTTPS" enabled="true">
<match serverVariable="RESPONSE_Strict_Transport_Security"
pattern=".*" />
<conditions>
<add input="{HTTPS}" pattern="on" ignoreCase="true" />
</conditions>
<action type="Rewrite" value="max-age=31536000" />
</rule>
</outboundRules>
</rewrite>
</system.webServer>
</configuration>
原答案(2015年12月4日取代)
基本上
protected void Application_BeginRequest(Object sender, EventArgs e)
{
if (HttpContext.Current.Request.IsSecureConnection.Equals(false) && HttpContext.Current.Request.IsLocal.Equals(false))
{
Response.Redirect("https://" + Request.ServerVariables["HTTP_HOST"]
+ HttpContext.Current.Request.RawUrl);
}
}
它会被放到global。asax。cs(或global。asax。vb)
我不知道如何在web.config中指定它
这是基于@特洛伊·亨特的更全面的回答。将这个函数添加到Global.asax.cs中的WebApplication类中:
protected void Application_BeginRequest(Object sender, EventArgs e)
{
// Allow https pages in debugging
if (Request.IsLocal)
{
if (Request.Url.Scheme == "http")
{
int localSslPort = 44362; // Your local IIS port for HTTPS
var path = "https://" + Request.Url.Host + ":" + localSslPort + Request.Url.PathAndQuery;
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location", path);
}
}
else
{
switch (Request.Url.Scheme)
{
case "https":
Response.AddHeader("Strict-Transport-Security", "max-age=31536000");
break;
case "http":
var path = "https://" + Request.Url.Host + Request.Url.PathAndQuery;
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location", path);
break;
}
}
}
(要在本地构建中启用SSL,请在项目的Properties dock中启用它)
如果你不能在IIS中设置这个,我会做一个HTTP模块,为你重定向:
using System;
using System.Web;
namespace HttpsOnly
{
/// <summary>
/// Redirects the Request to HTTPS if it comes in on an insecure channel.
/// </summary>
public class HttpsOnlyModule : IHttpModule
{
public void Init(HttpApplication app)
{
// Note we cannot trust IsSecureConnection when
// in a webfarm, because usually only the load balancer
// will come in on a secure port the request will be then
// internally redirected to local machine on a specified port.
// Move this to a config file, if your behind a farm,
// set this to the local port used internally.
int specialPort = 443;
if (!app.Context.Request.IsSecureConnection
|| app.Context.Request.Url.Port != specialPort)
{
app.Context.Response.Redirect("https://"
+ app.Context.Request.ServerVariables["HTTP_HOST"]
+ app.Context.Request.RawUrl);
}
}
public void Dispose()
{
// Needed for IHttpModule
}
}
}
然后将其编译为DLL,将其作为项目的引用添加到web.config中:
<httpModules>
<add name="HttpsOnlyModule" type="HttpsOnly.HttpsOnlyModule, HttpsOnly" />
</httpModules>
对于那些使用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上查看代码。
我花了一些时间寻找有意义的最佳实践,发现下面的方法非常适合我。我希望这能帮你节省时间。
使用配置文件(例如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>