asp.net에서 전체 사이트에 대해 https를 강제하는 가장 좋은 방법은 무엇입니까?

StackOverflow https://stackoverflow.com/questions/47089

문제

약 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에서 지정하는 방법을 모르겠습니다

다른 팁

당신이 할 수 있는 또 다른 일은 HSTS "Strict-Transport-Security" 헤더를 브라우저에 반환합니다.브라우저는 이를 지원해야 하지만(현재는 주로 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를 인식하지 못하는 브라우저는 헤더를 무시하지만 여전히 스위치 문에 의해 포착되어 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 패키지를 사용하고 다음 코드 줄을 추가하여 사이트 전체에서 엄격한 전송 보안을 활성화합니다.아래에 Preload 지시문을 추가하고 사이트를 HSTS 사전 로드 사이트.추가 정보 여기 그리고 여기.OWIN을 사용하지 않는 경우 다음에서 읽을 수 있는 Web.config 방법이 있습니다. NWebSec 대지.

// 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 체계를 포함합니다. 콘텐츠 보안 정책(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] 속성을 사용할 수 있습니다.

또한 밸런서 브랜드에 따라 다르며, 웹 멀티플렉서의 경우 http 헤더를 찾아야 합니다. X-WebMux-SSL-termination: true 들어오는 트래픽이 SSL임을 확인합니다.자세한 내용은 여기: http://www.cainetworks.com/support/redirect2ssl.html

위의 @Joe의 경우 "이로 인해 리디렉션 루프가 발생합니다.코드를 추가하기 전에는 잘 작동했습니다.어떤 제안이 있으십니까?– Joe 08 nov. 112011-11-08 4:13"

이런 일이 나에게도 일어났고 내가 믿고 있는 것은 웹 서버 앞에서 SSL 요청을 종료하는 로드 밸런서가 있었다는 것입니다.따라서 내 웹 사이트는 원래 브라우저가 "https"를 요청하더라도 항상 요청이 "http"라고 생각했습니다.

나는 이것이 약간 해킹적이라는 것을 인정하지만 나에게 효과가 있었던 것은 그 사람이 이미 한 번 리디렉션되었음을 알아내는 데 활용할 수 있는 "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;
        }
    }

나는 두 센트를 던질 것입니다. 만약에 IIS 서버 측에 액세스할 수 있으면 프로토콜 바인딩을 사용하여 HTTPS를 강제 실행할 수 있습니다.예를 들어, 다음과 같은 웹사이트가 있습니다. ㅋㅋㅋ.IIS에서는 두 개의 사이트를 설정합니다. ㅋㅋㅋ, 그리고 ㅋㅋㅋ (리디렉션).을 위한 ㅋㅋㅋ 만 구성 HTTPS 바인딩(및 FTP 필요한 경우 보안 연결을 통해 강제로 연결해야 합니다.을 위한 ㅋㅋㅋ (리디렉션) 만 구성 HTTP 제본.마지막으로, HTTP 리디렉션 섹션 ㅋㅋㅋ (리디렉션) 301 리디렉션을 다음으로 설정하세요. https://blah.com, 정확한 목적지가 활성화되어 있습니다.IIS의 각 사이트가 해당 사이트를 가리키는지 확인하세요. 소유하다 그렇지 않으면 루트 폴더 웹.구성 다 망쳐버릴 겁니다.또한 HSTS 브라우저의 후속 요청이 항상 HTTPS로 강제 적용되고 리디렉션이 발생하지 않도록 HTTPS 사이트에 구성됩니다.

이것은 @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을 활성화하려면 프로젝트의 속성 도크에서 활성화하세요)

-> 공개 클래스 HomeController 위에 [RequireHttps]를 추가하기만 하면 됩니다.제어 장치.

-> 그리고 GlobalFilters.Filters.Add(new RequireHttpsAttribute());를 추가합니다.Global.asax.cs 파일의 'protected void Application_Start()' 메소드에 있습니다.

전체 애플리케이션을 HTTPS로 강제 실행합니다.

나는 이해가 되는 모범 사례를 찾는 데 시간을 보냈고 나에게 완벽하게 맞는 다음을 찾았습니다.이것이 언젠가 당신을 구할 수 있기를 바랍니다.

사용 구성 파일 (예: 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>

ASP.NET Core를 사용하는 경우 너겟 패키지 SaidOut.AspNetCore.HttpsWithStrictTransportSecurity를 ​​사용해 볼 수 있습니다.

그런 다음 추가하기 만하면됩니다.

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

또한 https 체계를 사용하여 이루어진 모든 요청에 ​​HTTP StrictTransportSecurity 헤더를 추가합니다.

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

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에서 마우스 오른쪽 버튼을 클릭하고 관리자 권한으로 실행하세요.IIS 관리자에 표시되는 사이트 이름으로 Contoso를 바꿔야 합니다.

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년에 대한 자세한 내용은

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top