XMLHttpRequest: Network Error Access is denied - c#

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

Related

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

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.

HTTP Authorization header not working

I have the following angular code in which I had set the access_token also.
import { HttpClient } from '#angular/common/http';
import { Router } from '#angular/router';
import { HttpHeaders } from '#angular/common/http';
import { Headers, Response } from '#angular/http';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
// tslint:disable-next-line:max-line-length
'Authorization': 'bearer zhGMjEFn5SlPYPB4opK57CiPP02MuR-lk10rvYsGU0PcQUyo5U6JHaH5NgdmDpNHSfrkuDLZYIr3xAio_aG0WZbKWM28dgP9BN2i-ERS8PQ97_oXP93AVzHj60RivH5EsfImmEb3mPSSEw68lafAQHe4kQyEptkxTtYlfPczrdQR4hWVOkvA_Hk8JuxFQpUmj0ReRhP5xXfoJcsbOsLpSqcq2xj0GfapcGbvHiHR0hlXTXU9cELnGObXSgDVs1UDpM4pPcFb2CrG7aFCFoULYSe9yBpsn7RepYzomAIrF9hEo2_v_877x7HkVGAMBFd9Ij70jp5DbVumTkZuM9vRG8uDNwaOCsvbsEvZlBjpR4JO0b508vUyKPFctA5O6yzfLKMhpRtcj61HrvWrMqx3BehO-fSM-hmQUd1clH5dD_xX4P9wtR1oPZxNS7bVgUiNnUPkGocqMVS5p0SYyowzz7yKHu8tIpaTAQLPIbePcU6ewtGCBUSzUVZZB7jl5Vte'
})
};
this.Http.get<Teacher>(this.API_URL + 'Teacher/GetTeachers', { headers: this.header }).subscribe(data => {
this.Results = data as Teacher;
console.log('Results' + this.Results[0]);
console.log(this.Results);
});
After sending this request i am getting the following error.
The requested resource does not support http method 'OPTIONS'
Can anyone please help me out.
I had similar issue previously and I forgot Enabling cors at my server side.
public static void Register(HttpConfiguration config)
{
// Forgot adding below line.
config.EnableCors();
}
Is it something that you can check in your WebApiConfig.cs?
i had a similar issue when i was working on the back end of an application while a colleague was doing the front end in angular. i believe we were using basic authentication.
in the end what worked was adding Access-Control-Allow-Methods to the web.config.
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept, Cache-Control, Authorization, authorization" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
note: the above will allow prety much anything. you might want to limit the allow origin, and methods to what you need.
Edit: found the old code. i also made additions to Application_BeginRequest method in global.asax.cs
protected void Application_BeginRequest()
{
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
//These headers are handling the "pre-flight" OPTIONS call sent by the browser
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
hope it helps.
edit2: also found one more web.config change
<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>

Angular 2 & .Net Web Api 2.0 resource does not support method PUT

I have an angular 2/4 application which makes request to a .Net Web Api 2.0 using Windows authentication. I can make GET and DELETE requests that work perfectly. However when I try to do POST or PUT request I am getting the following error:
PUT
The requested resource does not support http method 'PUT
POST
The request entity's media type 'text/plain' is not supported for this resource. No MediaTypeFormatter is available to read an object of type from content with media type 'text/plain
I know windows authenticaion is working because I can make GET and DELETE Reqeusts. I have the Content-Type header set to application/json and I have handled cors and preflight with the following in my Application_BeginRequest method
var referrer = Request.UrlReferrer.GetLeftPart(UriPartial.Authority);
if (Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.Headers.Remove("Access-Control-Allow-Origin");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", referrer);
HttpContext.Current.Response.StatusCode = 200;
HttpContext.Current.Response.End();
}
if (Request.Headers.AllKeys.Contains("Origin"))
{
HttpContext.Current.Response.Headers.Remove("Access-Control-Allow-Origin");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", referrer);
}
I have also included the following in my web.config
Cors
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Credentials" value="true" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept, X-Pagination, Authorization" />
<add name="Access-Control-Expose-Headers" value="X-Pagination" />
</customHeaders>
</httpProtocol>
<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>
Windows Authentication
<authentication mode="Windows" />
<authorization>
<deny users="?" />
</authorization>
Any idea what could cause GET and DELETE to work but not POST, PUT, PATCH?
Update - Controller Methods
[Route("")]
[HttpPut]
public IHttpActionResult Put([FromBody] Header updatedEntity)
{
if (updatedEntity == null)
return BadRequest();
var entity = UnitOfWork.Headers.Get(updatedEntity.Id);
if (entity == null)
return NotFound();
// Setup up entity
UnitOfWork.Commit();
return StatusCode(HttpStatusCode.NoContent);
}
[HttpGet]
[Route("", Name = "RouteName")]
public IHttpActionResult List([FromUri] HeaderResourceParameters parameters)
{
parameters = parameters ?? new HeaderResourceParameters();
var recipients = UnitOfWork.Recipients.GetAll().ToList();
var entities = UnitOfWork.Headers.List(parameters)
.Select(o => new HeaderViewModel
{
// Entity Setup
});
if (entities == null)
return NotFound();
return Ok(entities);
}

Categories

Resources