在asp.net中对整个站点强制使用https的最佳方法?
时间:2020-03-05 18:48:35 来源:igfitidea点击:
大约6个月前,我推出了一个网站,每个请求都需要通过https进行。当时我可以确保确保对页面的每个请求都通过https的唯一方法是在页面加载事件中对其进行检查。如果请求不是通过http进行的,我将response.redirect(" https://example.com")
有没有更好的方法-理想的是在web.config中进行一些设置?
解决方案
回答
请使用HSTS
来自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中指定它的方法
回答
如果由于某种原因我们无法在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>
回答
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>
回答
这也取决于均衡器的品牌,对于Web多路复用器,我们需要查找http标头" X-WebMux-SSL-termination:true",以确认传入流量是ssl。此处的详细信息:http://www.cainetworks.com/support/redirect2ssl.html