【发布时间】:2009-03-26 14:38:53
【问题描述】:
如何确保我的用户不能物理输入 http: 来绕过我的 SSL 并确保每个页面都是 https:?
可能是我的母版页上的重定向?
【问题讨论】:
如何确保我的用户不能物理输入 http: 来绕过我的 SSL 并确保每个页面都是 https:?
可能是我的母版页上的重定向?
【问题讨论】:
这通常通过 IIS 配置或使用 ISAPI 过滤器来处理,但如果您想在应用程序代码中执行此操作,您可以在母版页的 Page_Init 事件中放置类似的内容...
If Not Request.IsSecure
Response.Redirect(Request.Url.AbsoluteUri.Replace("http://", "https://"))
End If
【讨论】:
我会使用单独的页面将所有 http url 重定向到 https,或者使用 IIS 配置中的“需要安全通道”选项,如果有人尝试访问非 https 页面,则会显示错误。
Here's 一个站点,其中包含将错误页面重定向到您站点的 https URL 的指南。
【讨论】:
以下内容基于 Josh Stodolas 的回答 (IsSecureConnection),但使用 UriBuilder 将方案更改为 https 而不是字符串替换。这种方法的好处是它不会将 URL 中所有出现的“http”更改为“https”。
if (!Request.IsSecureConnection)
{
UriBuilder newUri = new UriBuilder(Request.Url);
newUri.Scheme = Uri.UriSchemeHttps;
Response.Redirect(newUri.Uri.AbsoluteUri);
}
【讨论】:
我使用 HTTPModule 完成了这项工作,这样您就不必担心将代码放在每个母版页中(如果您有多个母版页)。此版本还关闭了 localhost 的重定向,因此您不必在自己的机器上安装 SSL。基本上你可以像这样创建一个新的 HTTP 模块:
Public Class RedirectToHttpsModule
Implements IHttpModule
Public Sub Dispose() Implements IHttpModule.Dispose
End Sub
Public Sub Init(ByVal context As HttpApplication) Implements IHttpModule.Init
AddHandler context.BeginRequest, AddressOf context_BeginRequest
End Sub
Private Sub context_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
Dim application As HttpApplication = TryCast(sender, HttpApplication)
If Not application.Request.IsSecureConnection And Not application.Request.IsLocal Then
application.Response.Redirect(application.Request.Url.ToString().Replace(application.Request.Url.Scheme, "https"))
End If
End Sub
End Class
您还必须在 web.config 中为 HTTPModule 添加适当的行:
<httpModules>
<add type="RedirectToHttpsModule" name="RedirectToHttpsModule" />
</httpModules>
【讨论】:
if(!String.Equals(Request.Url.Scheme,
"https",
StringComparison.OrdinalIgnoreCase)) { }
【讨论】:
如果您只想接受安全连接,请为端口 80 创建一个单独的服务,仅 重定向到 HTTPS。理想情况下,您会在 HTTP 重定向中保留请求的路径。
如果您只是想鼓励 HTTPS 连接进行浏览(例如,不关心机器人),请将其添加到您的页面:
<script type="text/javascript">
if(location.protocol=='http:')
location=location.toString().replace(/^http:/,'https:');
</script>
【讨论】: