sourcecode

asp.net에서 사이트 전체에 https를 강제 적용하는 최선의 방법?

codebag 2023. 4. 8. 08:28
반응형

asp.net에서 사이트 전체에 https를 강제 적용하는 최선의 방법?

약 6개월 전에 모든 요청이 https 이상일 필요가 있는 사이트를 롤아웃했습니다.이 시점에서 페이지에 대한 모든 요구가 https 이상임을 확인할 수 있는 유일한 방법은 페이지 로드 이벤트에서 확인하는 것이었습니다.요구가 http를 경유하지 않으면 응답합니다.http.https://example.com )

web.config의 설정이 이상적이면 더 좋은 방법이 있을까요?

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에서 지정하는 방법을 모릅니다.

외의 조작은, 「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 파일을 변경하여 기본적으로 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>

간단한 방법

ASP를 사용합니다.NET MVC Boilterplate 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);
            }
        }
    }
}

IIS10(Windows 10 및 Server 2016) 버전 1709 이후에서는 웹 사이트의 HSTS를 활성화하기 위한 새롭고 간단한 옵션이 있습니다.

Microsoft 에서는, 새로운 어프로치의 이점에 대해 설명하고 있습니다.또, 프로그램이나 ApplicationHost.config 파일(web.config 와 비슷하지만, 개개의 사이트 레벨이 아닌 IIS 레벨로 동작)을 직접 편집하는 것으로, 변경을 실장하는 방법의 다양한 예를 제공하고 있습니다.ApplicationHost.config는 C:\Windows\System32\inetsrv\config.

여기에서는 링크 부패를 방지하기 위한 두 가지 방법의 예를 설명했습니다.

방법 1 - ApplicationHost.config 파일을 직접 편집합니다.<site>붙여서 다음 .

<hsts enabled="true" max-age="31536000" includeSubDomains="true" redirectHttpToHttps="true" />

방법 2 - 명령줄:상승된 명령 프롬프트에서 다음을 실행합니다(즉, CMD에서 마우스 오른쪽을 누르고 관리자로 실행).Contoso를 IIS Manager에 표시되는 사이트 이름과 스왑해야 합니다.

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에 대한 자세한 내용은 여기를 참조하십시오.

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

이것은 @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을 활성화하려면 프로젝트의 속성 독에서 SSL을 활성화하십시오.)

또, 밸런서의 브랜드에 의해서도 다릅니다만, Web mux 의 경우는, http 헤더를 검색할 필요가 있습니다.X-WebMux-SSL-termination: true착신 트래픽이 ssl이었는지 확인하려면 여기를 클릭해 주세요.상세 http://www.cainetworks.com/support/redirect2ssl.html

위의 @Joe의 경우, "이것은 리다이렉트루프를 제공합니다.코드를 추가하기 전에는 정상적으로 동작했습니다.좋은 의견이라도 있나?– Joe 11월 8일 4:13 인치

저도 마찬가지입니다.웹 서버 앞에서 SSL 요구를 종료하는 로드밸런서가 있었던 것 같아요그래서 제 웹사이트는 원래 브라우저가 https로 요청해도 항상 "http"로 생각하고 있었습니다.

이게 좀 허술하다는 건 인정하지만, 제게 효과가 있었던 건 'Just Redirected' 속성을 구현해서 이미 한 번 리다이렉트된 사람이라는 걸 알 수 있게 하는 거였어요.따라서 리다이렉트를 보증하는 특정 조건을 테스트하고 그것들이 충족되면 리다이렉트 전에 이 속성(세션에 저장된 값)을 설정합니다.리다이렉트 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;
        }
    }

나는 내 의견을 말할 것이다.IIS 서버 측에 액세스할 수 있는 경우 프로토콜 바인딩을 사용하여 HTTPS를 강제 적용할 수 있습니다.예를 들어, Blah라는 웹사이트를 가지고 있습니다.IIS 에서는, Blah 와 Blah(리다이렉트)의 2 개의 사이트를 설정합니다.Blah의 경우,HTTPS바인딩(및FTP필요한 경우는, 반드시 안전한 접속에 강제적으로 접속해 주세요.Blah(리다이렉트)의 경우,HTTP바인드마지막으로 Blah(리다이렉트)HTTP 리다이렉트 섹션에서 301 리다이렉트를 다음과 같이 설정합니다.https://blah.com(정확한 행선지가 유효하게 되어 있는 경우).IIS 의 각 사이트가 자신의 루트 폴더를 가리키고 있는 것을 확인합니다.그렇지 않으면 Web.config 가 모두 망가집니다.그리고 또 꼭...HSTS브라우저에 의한 후속 요구가 항상 HTTPS로 강제되어 리다이렉트가 발생하지 않도록 HTTPS 사이트에서 설정됩니다.

이치에 맞는 베스트 프랙티스를 찾다가 다음과 같은 것이 나에게 딱 맞는 것을 알게 되었습니다.이게 언젠가 당신을 구해주길 바래요.

Config 파일 사용(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>

-> 퍼블릭클래스 HomeController : Controller 위에 [RequireHttps]를 추가합니다.

-> Global Filters 를 추가합니다.필터Global.asax.cs 파일의 'protected void Application_Start()' 메서드로 추가(new RequireHttpsAttribute()).

이로 인해 애플리케이션 전체가 HTTPS로 강제 설정됩니다.

ASP를 사용하는 경우.NET Core는 nuget 패키지 Said Out을 사용해 볼 수 있습니다.AspNetCore.Https With Strict Transport Security.

그러면 추가만 하면 됩니다.

app.UseHttpsWithHsts(HttpsMode.AllowedRedirectForGet, configureRoutes: routeAction);

또한 HTTP StrictTransportSecurity 헤더가 https 방식을 사용하여 이루어지는 모든 요구에 추가됩니다.

코드와 문서의 예:https://github.com/saidout/saidout-aspnetcore-httpswithstricttransportsecurity#example-code

언급URL : https://stackoverflow.com/questions/47089/best-way-in-asp-net-to-force-https-for-an-entire-site

반응형