2009-07-13 6 views
16

사용자가 HTTPS 만 사용하여 내 웹 사이트를 확인하고 강제로 확인하도록하려면 어떻게해야합니까? IIS를 통해이 작업을 수행 할 수 있지만 프로그래밍 방식으로 수행되는 방법을 알고 싶습니다.C# HTTPS를 확인하는 방법

+0

: http://www.jameskovacs.com/blog/HowToAutoRedirectToASSLsecuredSiteInIIS.aspx –

답변

20

당신은이 같은 HttpModule을 작성할 수 있습니다 {use SSL} SSL을 사용할지 여부를, 일부 조건이

/// <summary> 
/// Used to correct non-secure requests to secure ones. 
/// If the website backend requires of SSL use, the whole requests 
/// should be secure. 
/// </summary> 
public class SecurityModule : IHttpModule 
{ 
    public void Dispose() { } 

    public void Init(HttpApplication application) 
    { 
     application.BeginRequest += new EventHandler(application_BeginRequest); 
    } 

    protected void application_BeginRequest(object sender, EventArgs e) 
    { 
     HttpApplication application = ((HttpApplication)(sender)); 
     HttpRequest request = application.Request; 
     HttpResponse response = application.Response; 

     // if the secure connection is required for backend and the current 
     // request doesn't use SSL, redirecting the request to be secure 
     if ({use SSL} && !request.IsSecureConnection) 
     { 
      string absoluteUri = request.Url.AbsoluteUri; 
      response.Redirect(absoluteUri.Replace("http://", "https://"), true); 
     } 
    } 
} 

.

편집 :

<system.web> 
    <httpModules> 
     <!--Used to redirect all the unsecure connections to the secure ones if necessary--> 
     <add name="Security" type="{YourNamespace}.Handlers.SecurityModule, {YourAssembly}" /> 
     ... 
    </httpModules> 
</system.web> 
+0

대부분의 웹 애플리케이션은 알렉스로 표시된 바와 같이 같은 코드를 포함 할 수 _global.asax_ 페이지가 있습니다. Application_BeginRequest 처리기 만 제공하십시오. – Rajiv

+0

내 문제와 관련하여 도움이 된 것이 요청입니다.IsSecureConnection은 알렉스처럼 var 명명 된 요청을 작성하지 않는 한이 경우 요청을 대문자로 작성합니다. 명심할 것. –

+1

작은 메모가 있습니다 :'validation' 태그의'validateIntegratedModeConfiguration' 속성이'false'로 설정된'system.webServer'에서 통합 모드 구성을 비활성화해야합니다 ([this answer] (http://stackoverflow.com) 참조)./a/4210026)를 참조하십시오. 또한 IIS Express 또는 IIS 6을 사용하려면 [이 다른 대답] (http://stackoverflow.com/a/963975) –

5

당신은 C#을에 VB.NET에서이 변환해야 할 것이다, 그러나 이것은이다 : 그리고, 물론, web.config에 모듈 정의를 추가하는 것을 잊지 마세요 내 사이트에서 사용하는 내용 :

Imports System.Web.HttpContext 

Public Shared Sub SetSSL(Optional ByVal bEnable As Boolean = False) 
    If bEnable Then 
    If Not Current.Request.IsSecureConnection Then 
     Dim strHTTPS As String = "https://www.mysite.com" 
     Current.Response.Clear() 
     Current.Response.Status = "301 Moved Permanently" 
     Current.Response.AddHeader("Location", strHTTPS & Current.Request.RawUrl) 
     Current.Response.End() 
    End If 
    Else 
    If Current.Request.IsSecureConnection Then 
     Dim strHTTP As String = "http://www.mysite.com" 
     Current.Response.Clear() 
     Current.Response.Status = "301 Moved Permanently" 
     Current.Response.AddHeader("Location", strHTTP & Current.Request.RawUrl) 
     Current.Response.End() 
    End If 
    End If 
End Sub 

다른 기술보다 더 많은 코드가 있지만 그 이유가 있습니다. 이 방법은 그것이 있어야 할 모드에 있지 않을 때만 리다이렉트 할 것입니다. 리디렉션을하면 301 (영구적 인) 리다이렉션을합니다. 검색 엔진이 301 리디렉션을 따르고 동일한 페이지를 두 번 (http 및 https 모드에서) 인덱싱 할 가능성을 방지하는 이점이 있습니다. 이것을 Response.Redirect의 기본 동작 (302 임시 리디렉션)과 비교할 수 있습니다. 예를 들어 Google은 같은 방식으로 처리하지 않습니다. 임시 리디렉션을 기반으로 색인을 변경하지 않습니다.

그래서 당신은 당신이 SSL 암호화되고 싶은 페이지에 있다면, 다음과 같이 호출 :

그렇지 않으면

SetSSL (참) :

SetSSL (거짓)

그리고 전역 적으로 적용해야 할 필요가 있다면 global.asax의 Application_BeginRequest에서 SetSSL (True)를 호출합니다. SSL은 약간 느려지므로주의하십시오. 이러한 이유로 저는 http와 https 사이를 전환 할 때 대개 매우 선택적입니다. 실제로 내가 개발 한 수십 개의 사이트 중 전체 사이트에서 SSL을 사용하는 사이트는 2 개뿐입니다.

1

IIR 당신은 당신이 다음 사용되는 어떤 프로토콜을 확인할 수 있습니다 도메인에 대한 요청 (HttpContext.Current.Request) (HTTP, HTTPS, FTP를, 등)

10

비트 하드 코딩하지만 straighforward를 확인하실 수 있습니다!

if (!HttpContext.Current.Request.IsSecureConnection) 
{ 
    Response.Redirect("https://www.foo.com/foo/"); 
} 
+1

+1을 참고해야합니다. http 모듈은 과도한 것처럼 보이지만 여기에는 짧고 달콤하기 때문에 감사합니다. –

+1

간단하고 짧은 작품, – dvdmn

0

system.webServer 태그 아래 web.config에 다시 쓰기 규칙을 설정할 수도 있습니다. 예를 들면 : 이것처럼

<rewrite> 
     <rules> 
     <rule name="Redirect to HTTPS" stopProcessing="true"> 
      <match url="(.*)" /> 
      <conditions> 
      <add input="{HTTP_HOST}" matchType="Pattern" pattern="^localhost(:\d+)?$" negate="true" ignoreCase="true" /> 
      <add input="{HTTP_HOST}" matchType="Pattern" pattern="^127\.0\.0\.1(:\d+)?$" negate="true" /> 
      <add input="{HTTPS}" pattern="off" /> 
      </conditions> 
      <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" /> 
     </rule> 
     </rules> 
    </rewrite> 
관련 문제