有没有更好的方法--最好是在web.config中设置?
有没有更好的方法--最好是在web.config中设置?
<?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中指定的方法
另外一件你可以做的事情是使用HSTS,通过向浏览器返回“Strict-Transport-Security”标头。浏览器必须支持此功能(目前主要是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。
if(!Request.IsLocal)
中。 - Justin J Stark这个 IIS7 模块可以让你进行重定向。
<rewrite>
<rules>
<rule name="Redirect HTTP to HTTPS" stopProcessing="true">
<match url="(.*)"/>
<conditions>
<add input="{HTTPS}" pattern="^OFF$"/>
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="SeeOther"/>
</rule>
</rules>
</rewrite>
较为困难的方式
1 - 将RequireHttpsAttribute添加到全局过滤器中:
GlobalFilters.Filters.Add(new RequireHttpsAttribute());
2- 强制使用SSL / TLS的防伪令牌:
AntiForgeryConfig.RequireSsl = true;
3 - 通过更改Web.config文件,要求Cookies默认使用HTTPS:
<system.web>
<httpCookies httpOnlyCookies="true" requireSSL="true" />
</system.web>
4 - 使用NWebSec.Owin NuGet包,并添加以下代码行以启用整个站点的严格传输安全性。不要忘记在下面添加Preload指令并将您的站点提交到HSTS Preload site。更多信息here和here。请注意,如果您没有使用OWIN,则可以在NWebSec网站上查看Web.config方法。
// app is your OWIN IAppBuilder app in Startup.cs
app.UseHsts(options => options.MaxAge(days: 30).Preload());
5 - 使用NWebSec.Owin 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 - 在使用任何URL时,请包含https方案。 内容安全策略(CSP) HTTP标头和子资源完整性(SRI)在某些浏览器中无法正确处理模拟方案。更好的方法是明确使用HTTPS。例如:
<script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.4/bootstrap.min.js"></script>
简单快捷的方法
使用ASP.NET MVC Boilerplate Visual Studio项目模板生成一个已包含所有这些内容和更多功能的项目。你也可以在GitHub上查看代码。
<authentication mode="Forms">
,则需要在内部添加<forms requireSSL="true">
。 - PlutoRequireHttpsAttribute
会重定向。只要你有它,就应该没问题了。 - Muhammad Rehan Saeedusing 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>
Init
方法中会出现类似于app.BeginRequest += new OnBeginRequest;
的代码,并且OnBeginRequest
方法会包含当前Init
方法所包含的内容。你确定这个模块能够正常工作吗? - Jakub Šturc<add key="HttpsServer" value="stage"/>
or
<add key="HttpsServer" value="prod"/>
2) 在您的Global.asax文件中添加以下方法。
void Application_BeginRequest(Object sender, EventArgs e)
{
//if (ConfigurationManager.AppSettings["HttpsServer"].ToString() == "prod")
if (ConfigurationManager.AppSettings["HttpsServer"].ToString() == "stage")
{
if (!HttpContext.Current.Request.IsSecureConnection)
{
if (!Request.Url.GetLeftPart(UriPartial.Authority).Contains("www"))
{
HttpContext.Current.Response.Redirect(
Request.Url.GetLeftPart(UriPartial.Authority).Replace("http://", "https://www."), true);
}
else
{
HttpContext.Current.Response.Redirect(
Request.Url.GetLeftPart(UriPartial.Authority).Replace("http://", "https://"), true);
}
}
}
}
<site>
标签之间添加此行:<hsts enabled="true" max-age="31536000" includeSubDomains="true" redirectHttpToHttps="true" />
方法2 - 命令行: 在管理员权限的命令提示符中执行以下命令(即右键单击CMD并以管理员身份运行)。请记得将Contoso替换为在IIS管理器中显示的您的站点名称。
c:
cd C:\WINDOWS\system32\inetsrv\
appcmd.exe set config -section:system.applicationHost/sites "/[name='Contoso'].hsts.enabled:True" /commit:apphost
appcmd.exe set config -section:system.applicationHost/sites "/[name='Contoso'].hsts.max-age:31536000" /commit:apphost
appcmd.exe set config -section:system.applicationHost/sites "/[name='Contoso'].hsts.includeSubDomains:True" /commit:apphost
appcmd.exe set config -section:system.applicationHost/sites "/[name='Contoso'].hsts.redirectHttpToHttps:True" /commit:apphost
如果您在托管环境中的访问权限受限,那么该文章中微软提供的其他方法可能是更好的选择。
请记住,IIS10版本1709现在可在Windows 10上使用,但对于Windows Server 2016来说,它处于不同的发布轨道,并且不会作为补丁或服务包发布。有关1709的详细信息,请参见此处。
如果您的网站不支持配置SSL(即应该能够打开/关闭https)- 您可以在任何您希望保护的控制器/控制器操作上使用[RequireHttps]属性。
这是基于@Troy Hunt的更完整的答案。将此函数添加到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,请在项目的“属性”窗口中启用它。
我花了一些时间寻找有意义的最佳实践,并发现以下内容对我非常有效。希望这可以为您节省一些时间。
使用配置文件(例如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>