Disallowing HTTP verbs: System.Web.HttpMethodNotAllowedHandler is never invoked - c#

On my site, I want to disallow HTTP HEAD requests and have them answered with the 405 status code (Method not allowed). To achieve this I have the following in my web.config file:
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<remove name="TelemetryCorrelationHttpModule" />
<add name="TelemetryCorrelationHttpModule" type="Microsoft.AspNet.TelemetryCorrelation.TelemetryCorrelationHttpModule, Microsoft.AspNet.TelemetryCorrelation" preCondition="integratedMode,managedHandler" />
<remove name="ApplicationInsightsWebTracking" />
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
</modules>
<handlers>
<clear />
<add name="DenyHead" path="*" verb="HEAD" type="System.Web.HttpMethodNotAllowedHandler" />
<add name="DebugAttachHandler" path="DebugAttach.aspx" verb="DEBUG" type="System.Web.HttpDebugHandler" preCondition="integratedMode,runtimeVersionv4.0" />
<add name="StaticFile" path="*" verb="*" modules="StaticFileModule" resourceType="Either" requireAccess="Read" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,POST,DEBUG" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
<security>
<requestFiltering allowDoubleEscaping="true">
<verbs allowUnlisted="false">
<add verb="GET" allowed="true" />
<add verb="POST" allowed="true" />
<add verb="HEAD" allowed="true" />
<add verb="DEBUG" allowed="true" />
</verbs>
</requestFiltering>
</security>
</system.webServer>
Unfortunately, this doesn't work - I'm receiving bog-standard 404s instead.
Enabling failed request tracing yields the following:
20 HANDLER_CHANGED OldHandlerName
NewHandlerName DenyHead
NewHandlerType System.Web.HttpMethodNotAllowedHandler
...
61 AspNetPipelineEnter Data1 <Application_BeginRequest in my ASP.NET application>
...
135 HANDLER_CHANGED OldHandlerName System.Web.HttpMethodNotAllowedHandler
NewHandlerName System.Web.Mvc.MvcHandler
...
169 MODULE_SET_RESPONSE_ERROR_STATUS Notification EXECUTE_REQUEST_HANDLER
HttpStatus 404
This seems to show that the DenyHead handler is somehow being replaced/overridden by my MVC application, but there's no code in my app that does anything of the sort.
I've tried alternative recommendations such as the answers here, but they give the same result.
Request filtering isn't an option because the status code it returns is not configurable (it always returns a 404).
Action filters aren't an option because they won't be hit for static content, and I don't want to send everything through the MVC pipeline.

You can create action filter, and check for request method. If it is "HEAD", you can reject request by settings Result property on filterContext and set statuscode to 405 method not allowed.
Or You can check above logic for Application_BeginRequest in Global.aspx and do the same.

I wouldn't use IIS configuration as it gets you dependant on IIS, even though you might already be. Using a filter removes that dependency, just like that:
public class VerbFilter : IAsyncActionFilter
{
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
if (context.HttpContext.Request.Method == "HEAD")
{
context.Result = new StatusCodeResult(405);
}
else
{
await next();
}
}
}

Related

How to configure Application Insights with instrumentation keys from multiple environments in WCF?

If I set up my WCF project with an ApplicationInsights.config file as outlined in this Microsoft documentation, and data is logged to Application Insights (using the hardcoded instrumentation key) as expected.
Is there any way to specify instrumentation keys on a per-environment basis when using the ApplicationInsights.config file?
The config file looks like this:
<?xml version="1.0" encoding="utf-8"?>
<ApplicationInsights xmlns="http://schemas.microsoft.com/ApplicationInsights/2013/Settings">
<TelemetryInitializers>
<Add Type="Microsoft.ApplicationInsights.DependencyCollector.HttpDependenciesParsingTelemetryInitializer, Microsoft.AI.DependencyCollector" />
<Add Type="Microsoft.ApplicationInsights.WindowsServer.AzureRoleEnvironmentTelemetryInitializer, Microsoft.AI.WindowsServer" />
<Add Type="Microsoft.ApplicationInsights.WindowsServer.BuildInfoConfigComponentVersionTelemetryInitializer, Microsoft.AI.WindowsServer" />
<Add Type="Microsoft.ApplicationInsights.Web.WebTestTelemetryInitializer, Microsoft.AI.Web" />
<Add Type="Microsoft.ApplicationInsights.Web.SyntheticUserAgentTelemetryInitializer, Microsoft.AI.Web">
<!-- Extended list of bots:
search|spider|crawl|Bot|Monitor|BrowserMob|BingPreview|PagePeeker|WebThumb|URL2PNG|ZooShot|GomezA|Google SketchUp|Read Later|KTXN|KHTE|Keynote|Pingdom|AlwaysOn|zao|borg|oegp|silk|Xenu|zeal|NING|htdig|lycos|slurp|teoma|voila|yahoo|Sogou|CiBra|Nutch|Java|JNLP|Daumoa|Genieo|ichiro|larbin|pompos|Scrapy|snappy|speedy|vortex|favicon|indexer|Riddler|scooter|scraper|scrubby|WhatWeb|WinHTTP|voyager|archiver|Icarus6j|mogimogi|Netvibes|altavista|charlotte|findlinks|Retreiver|TLSProber|WordPress|wsr-agent|http client|Python-urllib|AppEngine-Google|semanticdiscovery|facebookexternalhit|web/snippet|Google-HTTP-Java-Client-->
<Filters>search|spider|crawl|Bot|Monitor|AlwaysOn</Filters>
</Add>
<Add Type="Microsoft.ApplicationInsights.Web.ClientIpHeaderTelemetryInitializer, Microsoft.AI.Web" />
<Add Type="Microsoft.ApplicationInsights.Web.AzureAppServiceRoleNameFromHostNameHeaderInitializer, Microsoft.AI.Web" />
<Add Type="Microsoft.ApplicationInsights.Web.OperationNameTelemetryInitializer, Microsoft.AI.Web" />
<Add Type="Microsoft.ApplicationInsights.Web.OperationCorrelationTelemetryInitializer, Microsoft.AI.Web" />
<Add Type="Microsoft.ApplicationInsights.Web.UserTelemetryInitializer, Microsoft.AI.Web" />
<Add Type="Microsoft.ApplicationInsights.Web.AuthenticatedUserIdTelemetryInitializer, Microsoft.AI.Web" />
<Add Type="Microsoft.ApplicationInsights.Web.AccountIdTelemetryInitializer, Microsoft.AI.Web" />
<Add Type="Microsoft.ApplicationInsights.Web.SessionTelemetryInitializer, Microsoft.AI.Web" />
</TelemetryInitializers>
<TelemetryModules>
<Add Type="Microsoft.ApplicationInsights.DependencyCollector.DependencyTrackingTelemetryModule, Microsoft.AI.DependencyCollector">
<ExcludeComponentCorrelationHttpHeadersOnDomains>
<!--
Requests to the following hostnames will not be modified by adding correlation headers.
Add entries here to exclude additional hostnames.
NOTE: this configuration will be lost upon NuGet upgrade.
-->
<Add>core.windows.net</Add>
<Add>core.chinacloudapi.cn</Add>
<Add>core.cloudapi.de</Add>
<Add>core.usgovcloudapi.net</Add>
</ExcludeComponentCorrelationHttpHeadersOnDomains>
<IncludeDiagnosticSourceActivities>
<Add>Microsoft.Azure.EventHubs</Add>
<Add>Microsoft.Azure.ServiceBus</Add>
</IncludeDiagnosticSourceActivities>
</Add>
<Add Type="Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.PerformanceCollectorModule, Microsoft.AI.PerfCounterCollector">
<!--
Use the following syntax here to collect additional performance counters:
<Counters>
<Add PerformanceCounter="\Process(??APP_WIN32_PROC??)\Handle Count" ReportAs="Process handle count" />
...
</Counters>
PerformanceCounter must be either \CategoryName(InstanceName)\CounterName or \CategoryName\CounterName
NOTE: performance counters configuration will be lost upon NuGet upgrade.
The following placeholders are supported as InstanceName:
??APP_WIN32_PROC?? - instance name of the application process for Win32 counters.
??APP_W3SVC_PROC?? - instance name of the application IIS worker process for IIS/ASP.NET counters.
??APP_CLR_PROC?? - instance name of the application CLR process for .NET counters.
-->
</Add>
<Add Type="Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.QuickPulse.QuickPulseTelemetryModule, Microsoft.AI.PerfCounterCollector" />
<Add Type="Microsoft.ApplicationInsights.WindowsServer.AppServicesHeartbeatTelemetryModule, Microsoft.AI.WindowsServer" />
<Add Type="Microsoft.ApplicationInsights.WindowsServer.AzureInstanceMetadataTelemetryModule, Microsoft.AI.WindowsServer">
<!--
Remove individual fields collected here by adding them to the ApplicationInsighs.HeartbeatProvider
with the following syntax:
<Add Type="Microsoft.ApplicationInsights.Extensibility.Implementation.Tracing.DiagnosticsTelemetryModule, Microsoft.ApplicationInsights">
<ExcludedHeartbeatProperties>
<Add>osType</Add>
<Add>location</Add>
<Add>name</Add>
<Add>offer</Add>
<Add>platformFaultDomain</Add>
<Add>platformUpdateDomain</Add>
<Add>publisher</Add>
<Add>sku</Add>
<Add>version</Add>
<Add>vmId</Add>
<Add>vmSize</Add>
<Add>subscriptionId</Add>
<Add>resourceGroupName</Add>
<Add>placementGroupId</Add>
<Add>tags</Add>
<Add>vmScaleSetName</Add>
</ExcludedHeartbeatProperties>
</Add>
NOTE: exclusions will be lost upon upgrade.
-->
</Add>
<Add Type="Microsoft.ApplicationInsights.WindowsServer.DeveloperModeWithDebuggerAttachedTelemetryModule, Microsoft.AI.WindowsServer" />
<Add Type="Microsoft.ApplicationInsights.WindowsServer.UnhandledExceptionTelemetryModule, Microsoft.AI.WindowsServer" />
<Add Type="Microsoft.ApplicationInsights.WindowsServer.UnobservedExceptionTelemetryModule, Microsoft.AI.WindowsServer">
<!--</Add>
<Add Type="Microsoft.ApplicationInsights.WindowsServer.FirstChanceExceptionStatisticsTelemetryModule, Microsoft.AI.WindowsServer">-->
</Add>
<Add Type="Microsoft.ApplicationInsights.Web.RequestTrackingTelemetryModule, Microsoft.AI.Web">
<Handlers>
<!--
Add entries here to filter out additional handlers:
NOTE: handler configuration will be lost upon NuGet upgrade.
-->
<Add>Microsoft.VisualStudio.Web.PageInspector.Runtime.Tracing.RequestDataHttpHandler</Add>
<Add>System.Web.StaticFileHandler</Add>
<Add>System.Web.Handlers.AssemblyResourceLoader</Add>
<Add>System.Web.Optimization.BundleHandler</Add>
<Add>System.Web.Script.Services.ScriptHandlerFactory</Add>
<Add>System.Web.Handlers.TraceHandler</Add>
<Add>System.Web.Services.Discovery.DiscoveryRequestHandler</Add>
<Add>System.Web.HttpDebugHandler</Add>
</Handlers>
</Add>
<Add Type="Microsoft.ApplicationInsights.Web.ExceptionTrackingTelemetryModule, Microsoft.AI.Web" />
<Add Type="Microsoft.ApplicationInsights.Web.AspNetDiagnosticTelemetryModule, Microsoft.AI.Web" />
</TelemetryModules>
<ApplicationIdProvider Type="Microsoft.ApplicationInsights.Extensibility.Implementation.ApplicationId.ApplicationInsightsApplicationIdProvider, Microsoft.ApplicationInsights" />
<TelemetrySinks>
<Add Name="default">
<TelemetryProcessors>
<Add Type="Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.QuickPulse.QuickPulseTelemetryProcessor, Microsoft.AI.PerfCounterCollector" />
<Add Type="Microsoft.ApplicationInsights.Extensibility.AutocollectedMetricsExtractor, Microsoft.ApplicationInsights" />
<Add Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.AdaptiveSamplingTelemetryProcessor, Microsoft.AI.ServerTelemetryChannel">
<MaxTelemetryItemsPerSecond>5</MaxTelemetryItemsPerSecond>
<ExcludedTypes>Event</ExcludedTypes>
</Add>
<Add Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.AdaptiveSamplingTelemetryProcessor, Microsoft.AI.ServerTelemetryChannel">
<MaxTelemetryItemsPerSecond>5</MaxTelemetryItemsPerSecond>
<IncludedTypes>Event</IncludedTypes>
</Add>
</TelemetryProcessors>
<TelemetryChannel Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.ServerTelemetryChannel, Microsoft.AI.ServerTelemetryChannel" />
</Add>
</TelemetrySinks>
<!--
Learn more about Application Insights configuration with ApplicationInsights.config here:
http://go.microsoft.com/fwlink/?LinkID=513840
-->
<InstrumentationKey>your-instrumentation-key-here</InstrumentationKey>
</ApplicationInsights>
My web.config contains the following:
<system.web>
<compilation debug="true" targetFramework="4.7.2" />
<httpRuntime targetFramework="4.7.2" />
<httpModules>
<add name="TelemetryCorrelationHttpModule" type="Microsoft.AspNet.TelemetryCorrelation.TelemetryCorrelationHttpModule, Microsoft.AspNet.TelemetryCorrelation" />
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
</httpModules>
</system.web>
This documentation suggests that I can set the instrumentation key in code (such as in an AppInitialize method as suggested by this answer), but it doesn't seem to work.
TelemetryConfiguration configuration = TelemetryConfiguration.CreateDefault();
configuration.InstrumentationKey = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
While there appear to be some caveats to this solution (depending on your hosting strategy), it is sometimes possible to add a Global.asax, and use the Application_Start hook to inject your configuration (This answer assumes you're using config transforms).
For example:
using System;
namespace SomeWcfThing
{
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration.Active.InstrumentationKey =
System.Configuration.ConfigurationManager.AppSettings["InstrumentationKey"];
}
}
}
The correct approach is to use TelemetryConfiguration.CreateDefault() method to load any config from disk, then set/change additional values on the generated configuration.
Once the TelemetryConfiguration instance is created pass it to the constructor of TelemetryClient to create the client and start logging.

Access to XMLHttpRequest has been blocked

I'm trying to connect a flutter web app with C# API with sending and parameter in header "apikey" if I'm sending it the error shows in the browser console
Access to XMLHttpRequest at 'http://localhost:49986/...' from origin 'http://localhost:61306' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
If I removed the "apikey" the connection goes well without error
Web.config code
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Credentials" value="false"/>
<add name="Access-Control-Allow-Headers" value="Origin,Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token, apikey" />
<add name="Access-Control-Allow-Methods" value="POST, OPTIONS" />
</customHeaders>
</httpProtocol>
</system.webServer>
Dio part in the flutter web app
static Dio getDio() {
Dio dio = Dio();
dio.options.headers.addAll({"apikey": "xyz"});
return dio;
}
N.B: the request is working well on postman
Is it recommended to disable chrome CORS in development as it's 2 localhosts HTTP or it's not related?
Thanks in advance!
Edit:
postman test

Glimpse Security Policy failing because the requests to glimpse.axd don't show the current user

I'm having a problem with a Glimpse installation in a Sitecore 8.1 environment. I'm trying to create a simple Glimpse Security Policy which would check if the current user is a Sitecore admin.
if (!Sitecore.Context.User.IsAdministrator)
{
return RuntimePolicy.Off;
}
This is functionally the same as the example given in the sample code that Glimpse provides on installation through NuGet, which is,
var httpContext = policyContext.GetHttpContext();
if (!httpContext.User.IsInRole("Administrator"))
{
return RuntimePolicy.Off;
}
The problem is that when this code is hit, and the request is directed at glimpse.axd, the user is always reset to extranet\Anonymous. Sitecore always sets an anonymous user when there is none. Any requests that are not to the glimpse handler pass the check and set RuntimePolicy.On.
I have the following in the web.config
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule"/>
<add type="Sitecore.Web.RewriteModule, Sitecore.Kernel" name="SitecoreRewriteModule"/>
<add name="Glimpse" type="Glimpse.AspNet.HttpModule, Glimpse.AspNet" preCondition="integratedMode"/>
<add type="Sitecore.Nexus.Web.HttpModule,Sitecore.Nexus" name="SitecoreHttpModule"/>
<add type="Sitecore.Resources.Media.UploadWatcher, Sitecore.Kernel" name="SitecoreUploadWatcher"/>
<add type="Sitecore.IO.XslWatcher, Sitecore.Kernel" name="SitecoreXslWatcher"/>
<add type="Sitecore.IO.LayoutWatcher, Sitecore.Kernel" name="SitecoreLayoutWatcher"/>
<add type="Sitecore.Configuration.ConfigWatcher, Sitecore.Kernel" name="SitecoreConfigWatcher"/>
<remove name="Session"/>
<add name="Session" type="System.Web.SessionState.SessionStateModule" preCondition=""/>
<add type="Sitecore.Analytics.RobotDetection.Media.MediaRequestSessionModule, Sitecore.Analytics.RobotDetection" name="MediaRequestSessionModule"/>
<add type="Sitecore.Web.HttpModule,Sitecore.Kernel" name="SitecoreHttpModuleExtensions"/>
<add name="SitecoreAntiCSRF" type="Sitecore.Security.AntiCsrf.SitecoreAntiCsrfModule, Sitecore.Security.AntiCsrf"/>
</modules>
The question is, why are the requests that are meant for /glimpse.axd not passing along the same authentication cookies as requests to the rest of the site?

XMLHttpRequest: Network Error Access is denied

I have a MVC 4 application making http POSTS requests to a Web API application using angular. Everything works as expected on the development environment, but when deployed to our production environment I'm getting the following error in the console log of the browser
XMLHttpRequest: Network Error 0x80070005, Access is denied.
This looks like a CORS issue, I added the following code to my web.config
<system.webServer>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
<httpProtocol>
<customHeaders>
<clear />
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, HEAD, OPTIONS" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
</customHeaders>
</httpProtocol>
and followed the Enabling Cross-Origin Requests in ASP.NET Web API 2 to no avail. Is there anything else I'm missing?
Ok, I removed the following code from my web.config
<httpProtocol>
<customHeaders>
<clear />
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, HEAD, OPTIONS" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
</customHeaders>
</httpProtocol>
and wrote a custom CORS policy attribute class for my web api
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)]
public class CrestCorsPolicyAttribute : Attribute, ICorsPolicyProvider
{
private readonly CorsPolicy _policy;
public CrestCorsPolicyAttribute()
{
_policy = new CorsPolicy
{
AllowAnyMethod = true,
AllowAnyHeader = true
};
var allowedOrigins = ConfigurationManager.AppSettings["AllowedOrigins"].Split(',');
foreach (var allowedOrigin in allowedOrigins)
{
_policy.Origins.Add(allowedOrigin);
}
}
public Task<CorsPolicy> GetCorsPolicyAsync
(
HttpRequestMessage request,
CancellationToken cancellationToken
)
{
return Task.FromResult(_policy);
}
}
which I implemented from my Global.asax file
GlobalConfiguration.Configuration.EnableCors(new CrestCorsPolicyAttribute());

C# VirtualPathProvider Static-Pages

I've got a virtual path provider (VPP) that serves simple aspx pages.
The problem lies when I introduce static references such as *.css, *.jpg files, etc ...
I noticed my VPP is capturing these requests. I don't want this to happen.
I want the normal System.Web.StaticFileHandler to handler these requests.
I've added the following in my web config:
<system.web>
<httpHandlers>
<add verb="GET,HEAD" path="*.css" type="System.Web.StaticFileHandler" />
<add verb="GET,HEAD" path="*.js" type="System.Web.StaticFileHandler" />
<add verb="GET,HEAD" path="*.jpg" type="System.Web.StaticFileHandler" />
<add verb="GET,HEAD" path="*.gif" type="System.Web.StaticFileHandler" />
</httpHandlers>
</system.web>
But my VPP still handles these requests.
Any ideas?
cheers in advance
I guess the VirtualPathProvider is invoked for every request. You'll have to override the FileExists method to tell the runtime whether the request is handled by the VirtualPathProvider or not.

Categories

Resources