.net mvc主机头注入- http模块- 400 Bad Request

vptzau2j  于 2023-11-20  发布在  .NET
关注(0)|答案(1)|浏览(161)

我有一个减轻MVC应用程序中主机头注入的任务。除此之外,我想通过创建一个HTTP模块来实现白名单检查。
到目前为止,我正在使用这样的东西:
web.config条目:

  1. <system.webServer>
  2. <modules>
  3. <add name="TestHttpModule" type="MVC5TestApp.MyHttpModule, MVC5TestApp" />
  4. </modules>
  5. </system.webServer>

字符串
HTTP模块类:

  1. public class MyHttpModule: IHttpModule
  2. {
  3. public MyHttpModule() {}
  4. public void Init(HttpApplication application)
  5. {
  6. application.BeginRequest += new EventHandler(this.context_BeginRequest);
  7. application.EndRequest += new EventHandler(this.context_EndRequest);
  8. }
  9. public void context_BeginRequest(object sender, EventArgs e)
  10. {
  11. CheckForHostHeaderInjection();
  12. }
  13. public void context_EndRequest(object sender, EventArgs e)
  14. {
  15. // some code
  16. }
  17. public void Dispose() {}
  18. private void CheckForHostHeaderInjection()
  19. {
  20. // Currently, I am just comparing the following two ServerVariables.
  21. // I will add a method to compare "HTTP_HOST" value against a whitelist later.
  22. var httpHost = HttpContext.Current.Request.ServerVariables["HTTP_HOST"];
  23. var serverName = HttpContext.Current.Request.ServerVariables["SERVER_NAME"];
  24. if (!string.Equals(httpHost, serverName))
  25. {
  26. // What do I do in order to send back to the client a 400 Bad Request??
  27. }
  28. }
  29. }

n9vozmp4

n9vozmp41#

对于MVC,更简洁的解决方案是实现一个IActionFilter来执行验证。在OnActionExecuting中,您可以执行头部检查并强制响应(HTTP 400),以短路请求流的其余部分。
您的OnActionExecuting实现将如下所示。

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

字符串
请访问https://learn.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/controllers-and-routing/understanding-action-filters-cs#understanding-action-filters

相关问题