Access to XMLHttpRequest has been blocked - c#

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

Related

Disallowing HTTP verbs: System.Web.HttpMethodNotAllowedHandler is never invoked

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();
}
}
}

Web api Cross-Origin Request Blocked error when called Token service. Other services works

I have a web api project separate and a simple UI project separate. To access web api in the UI project i have enabled CORS as below in WebApiConfig.cs
var cors = new EnableCorsAttribute("http://localhost:49567", "*", "*","*");
config.EnableCors(cors);
In AccountController.cs when [Authorize] is disabled i am able to access the APIs from the UI html project page using ajax.
$.ajax({
type: "GET",
url: "http://localhost:51401/api/Account/UserInfo",
data: "",
contentType: "application/json; charset=utf-8",
success: VerifyResponse,
dataType: "json",
crossDomain: true,
failure: ajaxCallFailed});
But when i want to enable [Authorize] to create token authentication by calling /token first, the error Cross-Origin Request Blocked: repeats in the html.
$.ajax({
method: "POST",
url: "http://localhost:51401/Token",
data: {
username: $('#username').val(),
password: $('#password').val(),
grant_type: 'password'
},
contentType: "application/json",
success: VerifyResponse,
dataType: "json",
crossDomain: true,
failure: ajaxCallFailed
});
My web.config in web api project now after the edit made after suggested by #arista_14
<system.webServer>
<modules>
<remove name="FormsAuthentication" />
<remove name="ApplicationInsightsWebTracking" />
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
</modules>
<validation validateIntegratedModeConfiguration="false" />
<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-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Credentials" value="true" />
<add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS" />
</customHeaders>
</httpProtocol>
</system.webServer>
Now the error is :
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:51401/Token. (Reason: CORS preflight channel did not succeed).[Learn More]
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:51401/Token. (Reason: CORS request did not succeed).[Learn More]
I ran into same problem. Just put this code in web.config. It worked for me -
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Credentials" value="true" />
<add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS" />
</customHeaders>
</httpProtocol>
The reason you're getting cross-origin blocking happening is because of the ports being different. You specified this url in your CORS: http://localhost:49567
But then proceed to call it with this url: http://localhost:51401
Note the difference in ports. I actually had the same issue until I set my localhost port to something that doesn't change on a whim.
I also did the config another answer shows, which didn't work.

Add security headers to help protection from injection attacks in c# asp.net

I have a C# asp.net application.It was sent to security assessment and below were the risks.
-Missing "Content-Security-Policy" header
-Missing "X-Content-Type-Options" header
-Missing "X-XSS-Protection" header
-It was observed that server banner is getting disclosed in HTTP response.
-It was observed that service version is getting disclosed in HTTP response.
I have the below code in the web.cofig file
<httpProtocol>
<customHeaders>
<remove name="X-Powered-By"/>
<add name="X-Frame-Options" value="DENY"/>
<add name="X-XSS-Protection" value="1; mode=block"/>
<add name="X-Content-Type-Options" value="nosniff "/>
</customHeaders>
</httpProtocol>
I thought this will add the headers. But the security team says the issue is not fixed. Is there any alternate for this.And for the Banner disclosure, I don't have access to server. can I fix this within the application.
After research I found this: Inside Global.asax I have this code:
protected void Application_PreSendRequestHeaders()
{
// Response.Headers.Remove("Server");
Response.Headers.Set("Server", "My httpd server");
Response.Headers.Remove("X-AspNet-Version");
Response.Headers.Remove("X-AspNetMvc-Version");
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
var app = sender as HttpApplication;
if (app != null && app.Context != null)
{
app.Context.Response.Headers.Remove("Server");
}
}
Is this the correct fix. Please help
Adding and removing headers during Application_BeginRequest always leads to headaches with your server complaining about not being able to do things after headers are set.
Typically "X-AspNet-Version" and "X-AspNetMvc-Version" are IIS custom headers and removing them depends on the verion of IIS you are using.
With new versions of IIS you can set it in Web.Config:
<system.web>
<httpRuntime enableVersionHeader="false" />
</system.web>
In older version you need to use IIS manager (see https://www.google.com/search?q=iis+remove++X-AspNet-Version&ie=utf-8&oe=utf-8):
You can remove the MVC header in app_start in Global.asax
MvcHandler.DisableMvcResponseHeader = true;
Your web.config should work fine:
<add name="X-Frame-Options" value="DENY"/>
<add name="X-XSS-Protection" value="1; mode=block"/>
<add name="X-Content-Type-Options" value="nosniff "/>
If not, Application_PreSendRequestHeaders is an appropriate place to add or remove headers well.
HttpContext.Current.Response.Headers.Add("X-Frame-Options", "DENY");
HttpContext.Current.Response.Headers.Add("X-XSS-Protection", "1; mode=block");
HttpContext.Current.Response.Headers.Add("X-Content-Type-Options", "nosniff");
HttpContext.Current.Response.Headers.Remove("Server");
You can use the web developer console on your web browser (usually opened by hitting F12) and click on the network tab to see what headers the server is sending.
Ensure you add the httpProtocol in the system.webServer as shown below:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="X-Frame-Options" value="DENY" />
<add name="X-Xss-Protection" value="1; mode=block" />
<remove name="X-Powered-By" />
</customHeaders>
</httpProtocol>
</system.webServer>
To remove the "server" header, add the code below in your Global.asax file
protected void Application_PreSendRequestHeaders()
{
Response.Headers.Remove("Server");
}
You can add any header globally using web.config e.g.
<system.webServer>
<httpProtocol>
<customHeaders>
<remove name="X-Powered-By" />
<add name="Cache-Control" value="no-store" />
<add name="X-XSS-Protection" value="1; mode=block" />
<add name="X-Content-Type-Options" value="nosniff" />
<add name="Strict-Transport-Security" value="max-age=31536000" />
</customHeaders>
</httpProtocol>
</system.webServer>
Refer : Adding Custom Headers Globally

Web API + jQuery AJAX DELETE request returning 404

My ASP.NET WebAPI & MVC application is returning a 404 error when I request a PUT or DELETE. It used to be returning a 405, but I resolved that by enabling CORS. I have tried all sorts of different solutions (disabling WebDAV, change routes, put querystring in request), but none seem to have worked for me. I'm hoping I just missed something extremely simple. Here's relevant simplified code from each relevant file in my application:
jQuery AJAX request:
$.ajax({
url: "api/Signout?id=3",
type: "DELETE",
crossDomain: true,
});
SignoutController (GET and POST methods work from here just fine):
public void Delete([FromUri] int id)
{
//Do things
}
WebApiConfig routes:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
//For another part of the application
config.Routes.MapHttpRoute(
name: "SaveSignout",
routeTemplate: "api/{controller}/{signout}"
);
Web.config:
<system.webServer>
<httpProtocol>
<customHeaders>
<clear />
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
<modules>
<remove name="FormsAuthenticationModule" />
<remove name="WebDAVModule"/>
</modules>
<handlers>
<remove name="WebDAV" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit"
path="*."
verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS"
modules="IsapiModule"
scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll"
preCondition="classicMode,runtimeVersionv4.0,bitness64"
responseBufferLimit="0" />
</handlers>
</system.webServer>
RouteConfig.cs (saw this somewhere else on SO)
routes.IgnoreRoute("{*x}", new { x = #".*\.asmx(/.*)?" });
Fiddler DELETE request (simplified referer):
DELETE /api/Signout?id=45 HTTP/1.1
Host: localhost:51301
Connection: keep-alive
Cache-Control: no-cache
Authorization: Negotiate (large base64 here)
Pragma: no-cache
Accept: */*
Origin: http://localhost:51301
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36
Referer: http://localhost:51301/Home/Controller/Id
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Fiddler response:
HTTP/1.1 404 Not Found
Cache-Control: private
Content-Type: text/html; charset=utf-8
Server: Microsoft-IIS/8.0
X-SourceFiles: =?UTF-8?B? (base64 of full local path to api/Signout)
Persistent-Auth: true
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
WWW-Authenticate: Negotiate oRswGaADCgEAoxIEEAEAAABDh+CIwTbjqQAAAAA=
Date: Tue, 17 Feb 2015 18:05:18 GMT
Content-Length: 4966
It's just a slew of various "solutions" I've come across that all apparently worked for those involved. Where am I going wrong?
By default IIS does not serve DELETE requests: the system.webServer handlers defined in Web.Config can set how to process requests when your website's Application Pool has a "Managed pipeline mode" of Integrated (IIS7) or Classic (ISAPI 32 & 64 bit flavours). In your example, only ISAPI 64 bit is controlled. The following shows the other variations.
<system.webServer>
<handlers>
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
Reference:
Related Answer on SO
Extensionless URL Handler Background on MSDN Blog
Background on Classic/ISAPI vs Integrated on SO
Richaux is correct, IIS does not serve DELETE, PUT and other requests by default. However, the Web.config part in that answer is showing how it was done in the MVC4 template. When creating a MVC5 Web API project from the MVC5 template you'll see the relevant part that registers the handler for all verbs:
<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>
</system.webServer>

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());

Categories

Resources