2008-09-05 52 views
148

大约6个月前,我推出了一个网站,每个请求都需要通过https。我能找到的唯一方法就是在页面加载事件中检查它,以确保对页面的每个请求都通过https进行检查。如果请求不是通过http我会response.redirect(“https://example.com”)在asp.net中为整个网站强制https的最佳方式?

有没有更好的方法 - 理想情况下在web.config中的一些设置?

+0

检查我在这里回答http://stackoverflow.com/questions/33882350/iis-8-redirect-url-from-http-to-https/33882351#33882351 – 2015-11-23 22:59:33

回答

182

请使用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> 

原来的答案

基本上

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(或全局。 asax.vb)

我不知道的方式在web.config

+5

该作品,但对我来说很危险:当我试图在VS 2010中运行本地代码并运行此代码时,我的启动页面从未加载;相反,我刚收到“此网页不可用”消息。为了解决这个问题,我添加了第二个条件来测试url是否包含字符串“localhost”:如果没有,则强制https。 – mg1075 2011-08-25 13:43:17

+1

这是给我一个重定向循环。在我添加代码之前,它工作正常。有什么建议么? – Joe 2011-11-08 04:13:50

+0

+1,它正在重定向到服务器两次?第一个,当你明确重定向时,第二个,当你在Global.asax中重定向时? – Pankaj 2012-04-25 18:10:56

11

如果无法在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> 
79

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

做HTTP模块的另一个优点是,如果你只在提供的global.asax.cs它,它只检查后的Application_BeginRequest,这意味着你的应用程序没有完全保护的SSL;它只会首先尝试路由到SSL版本,然后用户可以剪切并粘贴没有SSL的URL并绕过它。

101

您可以做的另一件事是通过向浏览器返回“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。

0

对于@Joe以上,“这是给我一个重定向循环之前,我加入它工作得很好代码的任何建议。 - ?乔11月8日在'11 4:13”

这是发生在我身上以及我相信发生的事情是有一个负载均衡器在Web服务器前终止SSL请求。所以,我的网站总是认为请求是“http”,即使原始浏览器要求它是“https”。

我承认这是一个有点哈克,但什么工作对我来说是实施“JustRedirected”属性,我可以利用弄清楚已经重定向一次的人。因此,我测试了保证重定向的特定条件,如果满足,我在重定向之前设置此属性(存储在会话中的值)。即使第二次满足重定向的http/https条件,我也会绕过重定向逻辑并将“JustRedirected”会话值重置为false。你需要自己的条件测试逻辑,但这里有一个简单的实现物业:

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

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

如果SSL支持是在您的网站未配置(即应该能够把HTTPS开/关) - 你可以在您希望保护的任何控制器/控制器操作上使用[RequireHttps]属性。

3

你需要做的是:

1)添加一个关键的web.config内,根据生产或阶段服务器像下面

<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); 
      } 
     } 
    } 
} 
17

对于那些使用ASP.NET MVC。您可以使用以下在整个网站强制SSL/TLS通过HTTPS方式有两种:

困难的方法

1 - 的RequireHttpsAttribute添加到全局过滤器:

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

2 - 强制防伪标记使用SSL/TLS:

AntiForgeryConfig.RequireSsl = true; 

3 - 需要Cookie通过改变需要默认使用HTTPS Web.config文件:

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

4 - 使用NWebSec.Owin NuGet包,并添加以下代码行,使严格传输安全翻过网站。不要忘记在下面添加Preload指令并将您的网站提交到HSTS Preload site。更多信息herehere。请注意,如果您不使用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)。更多信息herehere

// 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方案。 Content Security Policy (CSP) HTTP标头和Subresource Integrity (SRI)在您在某些浏览器中模仿该方案时不会很好玩。明确HTTPS最好。例如

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

简单的方法

使用ASP.NET MVC Boilerplate Visual Studio项目模板来生成所有这一切以及更多在建项目,您还可以查看GitHub的代码。

0

我打算把我的两毛钱扔进去。IF你有权访问IIS服务器端,那么你可以通过使用协议绑定强制HTTPS。例如,您有一个名为Blah的网站。在IIS中,您将设置两个站点:BlahBlah(重定向)。对于布拉只配置HTTPS绑定(和FTP如果您需要,请确保强制通过安全连接)。对于Blah(重定向)只配置HTTP绑定。最后,在HTTP重定向部分Blah(重定向)请确保将301重定向设置为https://blah.com,并且启用了确切的目标。确保IIS中的每个站点都指向它的自己的根文件夹,否则Web.config将全部搞砸。另外,请确保在您的HTTPSed站点上配置了HSTS,以便浏览器的后续请求始终强制为HTTPS,并且不会发生重定向。

0

- >在公共类HomeController:Controller上简单添加[RequireHttps]。

- >然后添加GlobalFilters.Filters.Add(new RequireHttpsAttribute());在Global.asax.cs文件的'protected void Application_Start()'方法中。

这会强制您的整个应用程序使用HTTPS。

1

这是一个基于@Troy Hunt's的更全面的答案。此功能添加到您的WebApplicationGlobal.asax.cs

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启用它在属性坞项目)

相关问题