[C#] 전체 사이트에 대해 https를 강제 실행하는 asp.net의 가장 좋은 방법은 무엇입니까?

약 6 개월 전에 모든 요청이 https를 넘어야하는 사이트를 출시했습니다. 페이지에 대한 모든 요청이 https를 통과했는지 확인할 수있는 유일한 방법은 페이지로드 이벤트에서 페이지를 확인하는 것입니다. 요청이 http가 아닌 경우 response.redirect ( ” https://example.com “)

더 좋은 방법이 있습니까? 이상적으로 web.config의 일부 설정입니까?



답변

제발 사용 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에서 그것을 지정하는 방법을 모른다


답변

다른 방법 으로는 “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로 전송됩니다.


답변

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>


답변

ASP.NET MVC를 사용하는 경우 다음을 사용하여 두 가지 방법으로 전체 사이트에서 HTTPS를 통한 SSL / TLS를 강제 실행할 수 있습니다.

어려운 방법

1-글로벌 필터에 RequireHttpsAttribute를 추가하십시오.

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

2-위조 방지 토큰이 SSL / TLS를 사용하도록 강제 :

AntiForgeryConfig.RequireSsl = true;

3-Web.config 파일을 변경하여 쿠키가 기본적으로 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 (Public Key Pinning)를 활성화하려면 다음 코드 줄을 추가하십시오. 여기여기에 더 많은 정보가 있습니다 .

// 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 상용구 에서이 모든 훨씬 더 내장 된 프로젝트를 생성하려면 Visual Studio 프로젝트 템플릿을. 당신은 또한에 코드를 볼 수 있습니다 GitHub의 .


답변

어떤 이유로 든 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>


답변

당신이해야 할 일은 :

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


답변

사이트에서 SSL 지원을 구성 할 수없는 경우 (즉, https를 켜거나 끌 수 있어야 함)-보호하려는 컨트롤러 / 컨트롤러 작업에서 [RequireHttps] 속성을 사용할 수 있습니다.