asp.net 實現請求白名單

只容許白名單內的地址可發送請求或跳轉,通常用於權限控制或解決跨站請求僞造漏洞。web

攔截request請求,可使用Global.asax裏的Application_BeginRequest:app

 1   protected void Application_BeginRequest(object sender, EventArgs e)  2  {  3             //每次請求時第一個出發的事件,這個方法第一個執行
 4             HttpApplication app = (HttpApplication)sender;  5 
 6             if (!app.Request.IsLocal)  7  {  8                 string referer = app.Context.Request.Headers["Referer"];  9                 string local_addr = app.Context.Request.ServerVariables.Get("Local_Addr").ToString(); 10 
11                 if (!string.IsNullOrEmpty(referer) && !referer.StartsWith("http://" + local_addr) && !referer.StartsWith("https://" + local_addr)) 12  { 13                     string allowRequestURL = ConfigurationManager.AppSettings["allowRequestURL"]??""; 14                     if (string.IsNullOrEmpty(allowRequestURL) || allowRequestURL.Split('', ',').Count(d => referer.Trim().StartsWith(d)) == 0) 15  { 16                         Response.Write("Unauthorized request URL:" + referer); 17  Response.End(); 18  } 19  } 20         }

白名單放在web.config的appSettingsspa

1 <appSettings>
2   <!--容許請求的站點-->
3   <add key="allowRequestURL" value="cnblogs.com"/>
4 </appSettings>
相關文章
相關標籤/搜索