.net mvc主机头注入-HTTP模块-400错误的请求

我有一个任务来减轻MVC应用程序中的主机标头注入。除其他外,我想通过创建HTTP模块来实现白名单检查。

到目前为止,我正在使用类似这样的东西:

web.config条目:

  <system.webServer>
    <modules>
      <add name="TestHttpModule" type="MVC5TestApp.MyHttpModule,MVC5TestApp" />
    </modules>
  </system.webServer>

HTTP模块类:

public class MyHttpModule: IHttpModule 
{

    public MyHttpModule() {}

    public void Init(HttpApplication application) 
    {
        application.BeginRequest += new EventHandler(this.context_BeginRequest);
        application.EndRequest += new EventHandler(this.context_EndRequest);
    }

    public void context_BeginRequest(object sender,EventArgs e) 
    {
        CheckForHostHeaderInjection();
    }

    public void context_EndRequest(object sender,EventArgs e) 
    {
        // some code
    }

    public void Dispose() {}

    private void CheckForHostHeaderInjection()
    {
        // Currently,I am just comparing the following two ServerVariables.
        // I will add a method to compare "HTTP_HOST" value against a whitelist later.
        var httpHost = HttpContext.Current.Request.ServerVariables["HTTP_HOST"];
        var serverName = HttpContext.Current.Request.ServerVariables["SERVER_NAME"];

        if (!string.Equals(httpHost,serverName))
        {
            // What do I do in order to send back to the client a 400 Bad Request??
        }
    }
}
sdwdwz 回答:.net mvc主机头注入-HTTP模块-400错误的请求

对于MVC,更干净的解决方案是实施IActionFilter来执行验证。在OnActionExecuting中,您可以执行标头检查并强制其中的响应(您的HTTP 400)使其余请求流短路。

您的OnActionExecuting实现如下所示。

if(!ValidateWhiteListedHeaders(context.HttpContext.Request.Headers)){
  context.Result = new StatusCodeResult(400);
  return;
}

请参见https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/controllers-and-routing/understanding-action-filters-cs#understanding-action-filters

本文链接:https://www.f2er.com/3142367.html

大家都在问