207

約 6 か月前、すべてのリクエストが https 経由である必要があるサイトを公開しました。当時、ページへのすべてのリクエストが https 経由であることを確認する唯一の方法は、ページの読み込みイベントで確認することでした。リクエストが http 経由でない場合は、response.redirect(" https://example.com ")

より良い方法はありますか - 理想的には web.config のいくつかの設定ですか?

4

15 に答える 15

270

HSTS (HTTP Strict Transport Security)を使用してください。

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で指定する方法がわかりません

于 2008-09-05T23:42:16.480 に答える
90

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>
于 2010-02-15T22:46:14.327 に答える
24

ASP.NET MVC を使用している場合。以下を使用して、2 つの方法でサイト全体に SSL/TLS over HTTPS を強制できます。

ハードウェイ

1 - RequireHttpsAttribute をグローバル フィルターに追加します。

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

2 - 偽造防止トークンに SSL/TLS を使用するように強制します。

AntiForgeryConfig.RequireSsl = true;

3 - Web.config ファイルを変更して、Cookie が既定で HTTPS を要求するようにします。

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

4 - NWebSec.Owin NuGet パッケージを使用し、次のコード行を追加して、サイト全体で Strict Transport Security を有効にします。下に Preload ディレクティブを追加し、サイトをHSTS Preload サイトに送信することを忘れないでください。詳細については、こちらこちらをご覧ください。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 スキームを含めます。Content Security Policy (CSP) HTTP ヘッダーとSubresource Integrity (SRI)は、一部のブラウザーでスキームを模倣すると適切に機能しません。HTTPS について明示することをお勧めします。例えば

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

簡単な方法

Use the ASP.NET MVC Boilerplate Visual Studio project template to generate a project with this and much more built in. GitHubでコードを表示することもできます。

于 2015-03-18T15:29:42.527 に答える
13

何らかの理由で 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>
于 2008-09-06T00:03:16.977 に答える
5

あなたがする必要があるのは:

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);
            }
        }
    }
}
于 2014-10-07T09:06:43.347 に答える
4

バージョン 1709 以降の IIS10 (Windows 10 および Server 2016) には、Web サイトで HSTS を有効にするための新しい、より簡単なオプションがあります。

Microsoft は、新しいアプローチの利点をここで説明し、変更をプログラムで実装する方法、または ApplicationHost.config ファイル (web.config に似ていますが、個々のサイト レベルではなく IIS レベルで動作する) を直接編集する方法のさまざまな例を提供しています。 )。ApplicationHost.config は、C:\Windows\System32\inetsrv\config にあります。

ここでは、リンクの腐敗を回避するための 2 つの方法の例を概説しました。

方法 1 - ApplicationHost.config ファイルを直接編集する<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

アクセスが制限されているホスト環境にいる場合は、その記事で Microsoft が提供する他の方法の方が適している可能性があります。

IIS10 バージョン 1709 は現在 Windows 10 で利用できますが、Windows Server 2016 では別のリリース トラックにあり、パッチまたはサービス パックとしてはリリースされないことに注意してください。1709の詳細はこちら

于 2018-11-24T11:43:35.153 に答える
3

これは、@ Troy Hunt に基づくより完全な回答です。WebApplicationこの関数を のクラスに追加しますGlobal.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 を有効にするには、プロジェクトの [プロパティ] ドックで有効にします)

于 2016-09-10T11:57:41.533 に答える
2

上記の@Joeの場合、「これにより、リダイレクトループが発生します。コードを追加する前は、正常に機能しました。何か提案はありますか?– Joe Nov 8 '11at4:13」

これは私にも起こっていました、そして私が起こっていたと私が信じているのは、Webサーバーの前でSSL要求を終了するロードバランサーがあったということです。そのため、元のブラウザが「https」を要求した場合でも、私のWebサイトは常に要求が「http」であると考えていました。

これは少しハッキーだと認めますが、私にとってうまくいったのは、その人がすでに一度リダイレクトされていることを把握するために利用できる「JustRedirected」プロパティを実装することでした。そのため、リダイレクトを保証する特定の条件をテストし、それらが満たされている場合は、リダイレクトの前にこのプロパティ(セッションに格納されている値)を設定します。リダイレクトのhttp/https条件が2回満たされた場合でも、リダイレクトロジックをバイパスして、「JustRedirected」セッション値をfalseにリセットします。独自の条件付きテストロジックが必要になりますが、プロパティの簡単な実装は次のとおりです。

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

            return (bool)Session[RosadaConst.JUSTREDIRECTED];
        }
        set
        {
            Session[RosadaConst.JUSTREDIRECTED] = value;
        }
    }
于 2012-12-12T19:46:23.553 に答える
2

X-WebMux-SSL-termination: trueまた、バランサーのブランドにも依存します。Web Mux の場合、着信トラフィックが ssl であることを確認するには、http ヘッダーを探す必要があります。詳細はこちら: http://www.cainetworks.com/support/redirect2ssl.html

于 2010-11-16T02:31:49.087 に答える