MVC RequireHttps属性毫无价值?

时间:2013-01-03 16:45:15

标签: asp.net-mvc security razor https custom-attributes

我要求允许用户通过我的asp.net MVC应用程序中的表单更改密码。我的第一个想法是使用RequireHttps属性修饰ChangePassword操作。

但是,我仍然必须在属性启动之前发送未加密的密码并返回“所请求的资源只能通过SSL访问”。这打败了目的,不是吗?

我确信我只是困惑而且RequireHttps很有用;我想知道是否有办法使用RequireHttps来实现我的目标。或者,我想知道实现它的任何其他方式。

更新:

由于以下答案,我现在有了一些选项 - 我可以使用https在iframe中加载密码输入,这意味着来自它的任何帖子都将被加密。另外,我可以在构造post url的代码中将协议设置为https:

var url = '@Url.Action("changePassword", "Security", new { area = "" }, "https")'

我不确定哪个更好,但我会尝试第二个 - 欢迎任何评论。

3 个答案:

答案 0 :(得分:6)

您的应用程序无法控制是否启用了SSL。这仅取决于Web服务器配置。您唯一能做的就是确保您的应用程序不信任未通过线路加密的数据。 RequireHttps就是这么做的。使用此属性修饰的操作永远不会处理以纯文本格式发送的数据。

答案 1 :(得分:1)

注意:[RequireHttps]属性不处理HEAD请求 - 而是提供异常,因此某些蜘蛛或预取工具会在尝试访问您的网站时出错。

无论如何,最好在IIS中使用rewrite module执行此类操作。

    <rule name="Redirect to http" enabled="true" patternSyntax="Wildcard" stopProcessing="true">
        <match url="*" negate="false" />
        <conditions logicalGrouping="MatchAny">
            <add input="{HTTPS}" pattern="off" />
        </conditions>
        <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Found" />
    </rule>

从这里采取:https://blogs.technet.microsoft.com/dawiese/2016/06/07/redirect-from-http-to-https-using-the-iis-url-rewrite-module/

重要提示:迁移到新服务器时不要忘记重新安装重写模块 - 如果您忘记了,则会出现错误!

答案 2 :(得分:1)

RequireHttpsAttribute的实际用例是仅在请求身份验证时强制执行https://方案。并非在所有情况下。 RequireHttpsAttribute仅实现IAuthenticationFilter接口的OnAuthentication方法。

由于仅在InvokeAuthenticationFilters方法中调用OnAuthentication方法,因此我不会使用RequireHttpsAttribute属性。

要对某些控制器或操作正确执行https://,我会根据ActionFilterAttribute创建自己的属性:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class EnforceHttpsActionFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);

        if (new[] { "GET", "HEAD" }.Any(verb => String.Equals(filterContext.HttpContext.Request.HttpMethod, verb, StringComparison.OrdinalIgnoreCase))) ;
        {
            string url = "https://" + filterContext.HttpContext.Request.Url.Host + filterContext.HttpContext.Request.RawUrl;
            filterContext.Result = new RedirectResult(url);
        }
    }
}

要对整个网站强制执行https://,您可以从我用于示例应用的*.azurewebsites.net个实例的web.config markup中获得灵感。

  <system.webServer>
    <rewrite>
      <rules>
        <rule name="HTTPS Redirect in Azure">
          <match url="(.+)" />
          <conditions>
            <add input="{HTTPS}" pattern="^OFF$" />
            <add input="{HTTP_HOST}" pattern="^(.+)\.azurewebsites.net(.*)$" />
          </conditions>
          <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" appendQueryString="true" redirectType="SeeOther" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
相关问题