asp.net c# http에서 https로 리디렉션
그래서 제 코드에서 제 로그인 페이지가 http로 불리는지 감지하고 https로 리디렉션하려고 합니다.
저는 이 고양이의 가죽을 벗길 수 있는 코드 방법이 없다는 것을 알고 있지만, 기술적인 이유로 저는 코드로 그것을 하는 것에 지지를 받았습니다.
if (!Request.IsSecureConnection)
{
string redirectUrl = Request.Url.ToString().Replace("http:", "https:");
Response.Redirect(redirectUrl);
}
그래서 나는 이것을 내 안에 떨어뜨립니다.Page_Load(...)
디버거가 VS2008s IIS가 아닌 실제 IIS를 사용하는지 확인하고 debug를 누릅니다.
디버거에서 왈츠를 추며 응답을 누릅니다.리디렉션("https://localhost/StudentPortal3G/AccessControl/AdLogin.aspx"), f5를 누릅니다.
"Internet Explorer에서 웹 페이지를 표시할 수 없습니다. URL은 HTTPS가 아닌 HTTP입니다. 정보 오류를 가져오지 않습니다...디버거에서 실행되지 않는 것과 같은 일이 발생합니다.
그럼 내가 뭘 놓쳤을까요?로켓 과학은 아닌 것 같습니다. 블로그에서 비슷한 코드를 봤습니다.
내가 뭘 잘못하고 있는 거지?분명히 루키의 실수일 거라고 생각합니다만, 저는 그것을 보지 못하고 있습니다.
나는 할 것입니다.!Request.IsLocal
디버깅할 때 인증서가 적용된 실제 IIS 인스턴스를 사용하는 경우에는 문제가 되지 않습니다.
if (!Request.IsLocal && !Request.IsSecureConnection)
{
string redirectUrl = Request.Url.ToString().Replace("http:", "https:");
Response.Redirect(redirectUrl, false);
HttpContext.ApplicationInstance.CompleteRequest();
}
이한 것입니다. 여기서 " " ": " " " " " " MVC " " " 입니다.HttpContext
현재 컨텍스트를 포함하는 속성입니다. 당신이, 은 운이나웹양컨축경우참로는을 사용해야 할입니다.HttpContext.Current.ApplicationInstance.CompleteRequest()
.
참고: 프레임워크 문서에 따라 요청을 종료하는 권장 패턴과 일치하도록 업데이트했습니다.
페이지 핸들러에서 이 메서드를 사용하여 한 페이지에 대한 요청을 종료하고 다른 페이지에 대한 새 요청을 시작할 때 endResponse를 false로 설정한 다음 CompleteRequest 메서드를 호출합니다.endResponse 매개 변수에 true를 지정하면 이 메서드는 원래 요청에 대해 End 메서드를 호출합니다. 이 메서드는 요청이 완료될 때 ThreadAbortException 예외를 던집니다.이 예외는 웹 응용 프로그램 성능에 좋지 않은 영향을 미치므로 endResponse 매개 변수에 대해 false를 전달하는 것이 좋습니다.자세한 내용은 종료 방법을 참조하십시오.
보통 모든 페이지가 상속되는 기본 클래스의 OnPreInit에서 다음을 호출합니다.물론, 모든 페이지에서 이렇게 할 수 있습니다.하지만 지금은 그렇게 하고 싶지 않으시겠죠?
각 페이지에 대한 SSL 요구사항을 지정할 수 있도록 각 페이지에 대해 두 개의 속성이 있습니다(필수).SSL)을(를) 재정의하고 리디렉션하여 원하는 경우 확인할 수도 있습니다(IgnoreRequests 사용).SSL - 다시 쓰는 오류 페이지와 같은 페이지에 유용하며 암호화 여부를 알 수 없습니다.) 그러나 간단한 설정을 위해 이러한 페이지를 제거할 수 있습니다.
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
if (!IsPostBack)
RedirectAccordingToRequiresSSL();
...
}
/// <summary>
/// Redirect if necessary to ssl or non-ssl enabled URL dependant on RequiresSSL property setting.
/// </summary>
private void RedirectAccordingToRequiresSSL()
{
if (IgnoreRequiresSSL) return;
if (RequiresSSL)
{
if (!Request.IsSecureConnection) // Need to redirect to https
RedirectAccordingToRequiresSSL(Uri.UriSchemeHttps);
}
else if (Request.IsSecureConnection)
{
RedirectAccordingToRequiresSSL(Uri.UriSchemeHttp);
}
// Otherwise don't need to do any redirecting as already using the correct scheme
}
/// <summary>
/// Redirect as requested to specified scheme
/// </summary>
/// <param name="scheme"></param>
private void RedirectAccordingToRequiresSSL(string scheme)
{
var url = scheme + Uri.SchemeDelimiter + Request.Url.Authority + Request.Url.PathAndQuery;
Response.Redirect(url, false);
}
제 생각에는 다음과 같은 방법이 최선의 만능 접근법입니다.
세가지 이유
- 두 가지 모두에 효과가 있습니다.
MVC
그리고.Web API
…에서 행하고 있는 바와 같이IIS
레벨 - 로컬/디버깅 설정에는 영향을 주지 않습니다.(영구적인 리디렉션은 non을 디버깅할 때 사용자를 혼란스럽게 할 수 있습니다.
https
사용자의 PC에 있는 사이트) - 리디렉션을 사용하므로 으로 영구리션을사이모요자든다동이로음다로 이동합니다.
https
여러분의 음을추만하됩에 .<system.webServer>
프로젝트의 'Web.config' 섹션을 참조하십시오.
<system.webServer>
....
<rewrite>
<rules>
<rule name="HTTP to HTTPS redirect" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{HTTP_HOST}" pattern="localhost" negate="true" />
<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>
새 UriBuilder를 사용할 수도 있습니다.
Dim context As HttpContext = HttpContext.Current
If Not context.Request.IsSecureConnection Then
Dim secureUrl As New UriBuilder(context.Request.Url)
secureUrl.Scheme = "https"
secureUrl.Port = 443
context.Response.Redirect(secureUrl.ToString, False)
Return
End If
C#
HttpContext context = HttpContext.Current;
if (!context.Request.IsSecureConnection)
{
UriBuilder secureUrl = new UriBuilder(context.Request.Url);
secureUrl.Scheme = "https";
secureUrl.Port = 443;
context.Response.Redirect(secureUrl.ToString(), false);
}
https 리디렉션을 적용할 수 있었던 방법 중 하나는 다음과 같습니다.
앱 풀에서는 애플리케이션이 포트 443에서만 실행되므로 암호화되지 않은 세션이 발생할 가능성이 없습니다(암호화 체계가 취약성을 통해 깨지지 않는 한...).다음 코드를 가진 web.config 파일만 포함하는 동일한 IP 주소로 포트 80에 다른 응용 프로그램을 만들었습니다.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<httpRedirect enabled="true" destination="https://yourWebsiteURL.com" />
</system.webServer>
제 솔루션은 다음과 같습니다.
// Force HTTPS connection
if (!Request.IsSecureConnection)
{
var uri = new Uri(Request.Url.ToString());
var redirectUrl = Settings.CanonicalDomain + uri.PathAndQuery;
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location", redirectUrl);
Response.End();
}
에▁where디Settings.CanonicalDomain
HTTPS 호스트 이름입니다.301은 경우에 따라 적절한 응답일 수 있는 방향을 리디렉션합니다.
저는 또한 valfonso의 솔루션을 제안하고 싶지만, URL을 다시 쓰는 경우를 대비하여 약간의 수정을 가합니다(RawUrl은 Url과 다릅니다).
if (SPPage == SPPages.StartAutotrading && !Request.IsLocal && !Request.IsSecureConnection)
{
string redirectUrl = (Request.Url.ToString().Replace(Request.Url.PathAndQuery.ToString(), "") + Request.RawUrl).Replace("http:", "https:");
Response.Redirect(redirectUrl);
}
면책 사항 - 저는 이 프로젝트의 개발에 관여했습니다.
http://nuget.org/packages/SecurePages/ 을 사용하는 것이 좋습니다. 특정 페이지를 보호하거나 Regex를 사용하여 일치 항목을 정의할 수 있습니다.또한 정규식과 일치하지 않거나 직접 지정된 모든 페이지를 HTTP로 강제 적용합니다.
NuGet 을통설수있습을 할 수 .Install-Package SecurePages
문서는 다음과 같습니다. https://github.com/webadvanced/Secure-Page-manager-for-asp.net#secure-pages
단순 사용:
SecurePagesConfiguration.Urls.AddUrl("/cart");
또는
SecurePagesConfiguration.Urls.AddRegex(@"(.*)account", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Singleline);
개발 환경에서는 Visual Studio 내부에서 직접 디버그하는 인증서가 없는 코드 디렉터리와 다른 자체 서명 인증서와 함께 IIS가 설치된 별도의 게시 디렉터리를 원합니다. 시나리오에서 이리 서는에오나.!Request.IsLocal
개발 환경 어디에서도 작동하지 않기 때문에 이상적이지 않습니다. 심지어 인증서가 있는 IIS 디렉터리에서도 작동하지 않습니다.나는 이것을 선호합니다.
if (!IsPostBack && !HttpContext.Current.IsDebuggingEnabled)
{
// do http->https and https->http redirection here
}
HttpContext.Current.IsDebuggingEnabled
는 web.config의 compilation debug="true/false" 값을 기반으로 합니다.http 및 https 리디렉션을 로컬로 테스트해야 할 때 코드 디렉터리에서 true로 설정하고 게시 디렉터리에서 false로 설정합니다.
에 추가합니다.IsPostBack
필요하지 않을 때 추가 SSL 검사를 건너뛰어 더 효율적으로 작업(실행)할 수 있습니다.
Rewrite를 사용하지 않고 IIS에서 이 작업을 수행할 수 있는 간단한 방법:
- IIS SSL 설정:SSL을 필수로 설정합니다.
- IIS 오류 페이지: IIS 403 오류 코드를 변경하여 https URL로 리디렉션합니다.
HttpErrors 섹션의 web.config에서 추가할 수도 있습니다.
언급URL : https://stackoverflow.com/questions/5305443/asp-net-c-sharp-redirecting-from-http-to-https
'programing' 카테고리의 다른 글
Oracle FIRST/LAST에서 KEEP에 대한 설명 (0) | 2023.08.04 |
---|---|
주어진 HTML을 사용하여 동적으로 iframe 만들기 (0) | 2023.08.04 |
Android 모양 색상을 프로그래밍 방식으로 설정 (0) | 2023.08.04 |
Android에서 토스트의 위치를 변경하는 방법은 무엇입니까? (0) | 2023.08.04 |
스프링 부트 보안 - 우체부가 401을 무단으로 제공합니다. (0) | 2023.08.04 |