确保仅通过SSL访问页面

时间:2009-03-26 14:38:53

标签: c# asp.net ssl

如何确保我的用户无法在物理上键入http:绕过我的SSL并确保每个页面都是https:?

可能是我主页上的重定向?

6 个答案:

答案 0 :(得分:9)

这通常可以通过IIS配置或ISAPI过滤器来处理,但是如果你想在应用程序代码中执行它,你可以在主页的Page_Init事件中添加这样的东西......

If Not Request.IsSecure
    Response.Redirect(Request.Url.AbsoluteUri.Replace("http://", "https://"))
End If

答案 1 :(得分:2)

我只是将所有http网址重定向到https并使用单独的页面,或者在IIS配置中使用“require secure channel”选项,如果有人试图访问非https页面,则会显示错误。

Here's一个网站,其中包含将错误页面重定向到您网站的https网址的指南。

答案 2 :(得分:2)

以下内容基于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);
}

答案 3 :(得分:1)

我已经使用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>

答案 4 :(得分:0)

if(!String.Equals(Request.Url.Scheme,
                  "https",
                  StringComparison.OrdinalIgnoreCase)) { }

答案 5 :(得分:0)

如果您只想接受安全连接,请为重定向到HTTPS的端口80创建单独的服务。理想情况下,您将在HTTP重定向中保留请求的路径。

如果您只是想鼓励使用HTTPS连接进行浏览(例如,不关心机器人),请将其添加到您的网页中:

<script type="text/javascript">
if(location.protocol=='http:')
  location=location.toString().replace(/^http:/,'https:');
</script>
相关问题