The access-control-allow-headers token is absent from the CORS header 'Access-Control-Allow-Headers' during the CORS preflight process

I am facing an issue with two VS projects: one has MVC5 controllers exposed, while the other is an Angular client. I need the Angular client to be able to query the controllers. I have done some research and attempted the following steps:

  • I added the following code in the server's web config:

    <system.webServer>
        <httpProtocol>
           <customHeaders>
                <clear />
                <add name="Access-Control-Allow-Origin" value="*" />
            </customHeaders>
        </httpProtocol>
    <system.webServer>
    
  • I created a filter called 'AllowCrossSiteJsonAttribute' and used it on the controller's action:

    public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
            base.OnActionExecuting(filterContext);
        }
    }
    
  • In the Angular client, I implemented an interceptor as follows :

    app.factory("CORSInterceptor", [
        function()
        {
            return {
                request: function(config)
                {
                     config.headers["Access-Control-Allow-Origin"] = "*";
                     config.headers["Access-Control-Allow-Methods"] = "GET, POST, OPTIONS";
                     config.headers["Access-Control-Allow-Headers"] = "Content-Type";
                     config.headers["Access-Control-Request-Headers"] = "X-Requested-With, accept, content-type";
                     return config;
                }
         };
    }
    ]);
    
    app.config(["$httpProvider", function ($httpProvider) {
        $httpProvider.interceptors.push("CORSInterceptor");
    }]);
    

However, despite these changes, Firebug shows that my request looks like this :

OPTIONS //Login/Connect HTTP/1.1
Host: localhost:49815
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Origin: http://localhost:50739
Access-Control-Request-Method: POST
Access-Control-Request-Headers: access-control-allow-headers,access-control-allow-origin,content-type
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache

And the response I get is :

HTTP/1.1 200 OK
Allow: OPTIONS, TRACE, GET, HEAD, POST
Server: Microsoft-IIS/10.0
Public: OPTIONS, TRACE, GET, HEAD, POST
X-SourceFiles: =?UTF-8?B?RDpcVEZTXElVV2ViXEdhcE5ldFNlcnZlclxBU1BTZXJ2aWNlc1xMb2dpblxDb25uZWN0?=
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Headers: *
Access-Control-Request-Headers: X-Requested-With, accept, content-type
Date: Tue, 01 Sep 2015 13:05:23 GMT
Content-Length: 0

Despite all this, Firefox continues to block the request with the message :

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:49815//Login/Connect. (Reason: missing token 'access-control-allow-headers' in CORS header 'Access-Control-Allow-Headers' from CORS preflight channel).

Answer №1

Many times, I noticed that the discussions I came across were suggesting a number of unnecessary configuration steps, leading to confusion. The solution is actually quite straightforward...

If you simply want to send a cross-site request from an Angular client to an ASP controller:

  • No need for Angular interceptors.
  • No requirement for custom filters on the server-side.
  • All you have to do is make this one essential modification in the server's web.config file

    <system.webServer>
          <httpProtocol>
              <customHeaders>
                  <clear />
                  <add name="Access-Control-Allow-Origin" value="*" />
                  <add name="Access-Control-Allow-Headers" value="Content-Type"/>
              </customHeaders>
         </httpProtocol>
    </system.webServer>
    

Answer №2

One issue arises when certain browsers do not support the use of the * wildcard for the Access-Control-Allow-Headers header. Specifically, Firefox 69 and earlier versions are known to have this limitation. More information can be found at https://bugzilla.mozilla.org/show_bug.cgi?id=1309358.

To ensure consistent behavior across all browsers, it is recommended to explicitly specify the necessary header names within the Access-Control-Allow-Headers value that is sent back. For example, in the scenario mentioned:

Access-Control-Allow-Headers: Content-Type
.

An alternative approach to avoid hardcoding all header names is to have your server-side code extract the value from the Access-Control-Request-Headers request header sent by the browser, and then mirror this value in the Access-Control-Allow-Headers response header sent by your server.

Alternatively, you can utilize existing libraries to enable CORS on your server. Most CORS libraries will handle the process of mirroring the request-header value from Access-Control-Request-Headers to the response-header value of Access-Control-Allow-Headers for you automatically.

Answer №3

I've attempted to implement CORS in my .NET C# MVC app and Angular 8 client app, but unfortunately, it doesn't seem to be working as expected. I made the necessary changes in the web.config file by adding:

<httpProtocol>
  <customHeaders>
    <clear />
    <add name="Access-Control-Allow-Origin" value="http://localhost:4200" />
    <add name="Access-Control-Allow-Headers" value="Content-Type"/>
  </customHeaders>
</httpProtocol>

In addition, I also updated the global.axax.cs file with:

    void MvcApplication_AuthenticateRequest(object sender, EventArgs e)
    {
        Context.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost:4200");
    }

However, despite these changes, the issue persists. The response headers in Chrome show the correct values for Access-Control-Allow-Headers and Access-Control-Allow-Origin, but the request header is not as expected.

The required header should include x-iphoneclientid: 8E72FF50-548B, which is crucial for authentication in my filter class. Unfortunately, the condition to check for x-iphoneclientid in the headers does not seem to find the value, causing the request to be rejected before reaching the controller.

I have also added [EnableCors("*", "*", "*")] in my controller, but the problem remains unresolved. Any guidance on this matter would be greatly appreciated.

Thank you.

Answer №4

After encountering a similar issue and finding other solutions ineffective, I realized that the problem may have been due to my use of a newer framework. To address this, I turned to Microsoft's official documentation for guidance in resolving the issue in 2023. You can find the detailed steps provided by Microsoft here. Additionally, I've condensed the solution below.

To fix the problem, add the following code snippet to your Program.cs file:

string myAllowSpecificOrigins = "myAllowSpecificOrigins";

builder.Services.AddCors(
    options => {
        options.AddPolicy(
            name: myAllowSpecificOrigins, policy => {
                policy.WithOrigins("https://localhost:44434")
                .AllowAnyHeader()
                .AllowAnyMethod();
            }
        );
    }
);

app.UseCors(myAllowSpecificOrigins);

This configuration will enable specific ports to make cross-origin requests. Make sure to replace the localhost address and port with your own if they differ. It is crucial to place this code correctly within your Program.cs file - ensure that UseCors comes after UseRouting and before MapControllers (refer to the link for more detailed examples and explanation).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using AngularJs to create a couchdb document

const post_data = { "task_list": $scope.task_list, "uri": $scope.uri }; $http({ method: 'POST', url: 'http://127.0.0.1:5984/tasklist/' + $scope.task_list, data: post_data }) .success(function(data, status, headers, config) { ...

Having trouble with modifying command line arguments when executing test suites in AngularJS Protractor using Gulp

After setting parameters in the configuration file, I tried to override them at runtime but it doesn't seem to be working. The login is still using the username mentioned in the conf file. This is my config file: var Jasmine2HtmlReporter = require(& ...

Having trouble accessing the JSON result with Jquery

My controller has an action that returns JSON results, which I have tested and confirmed to be working properly. public JsonResult GetProductsByDepList(int id) { JsonResult jr = new JsonResult(); var _product = from a in DataContex ...

Stop ngRepeat flashing by implementing promises in AngularJS

I have a collection of items, let's call them Products, that I can manage using $resource. When displaying the collection on an index page, I want to show the items if there are any, and display a helpful message if the collection is empty. Controlle ...

Having trouble with CORS errors persisting despite configuring CORS options for Google Authentication on React/Node/Passport

Currently, I'm in the process of developing a basic application using React for the frontend and Node/Express/MongoDB for the backend. User authentication is being handled through Passport, with local authentication and Google authentication both func ...

Having difficulty retrieving the value of a dynamically selected radio button in AngularJS

Having trouble with selecting radio options in my code, need some assistance to fix it. Check out my Plnkr Code - http://plnkr.co/edit/MNLOxKqrlN5ccaUs5gpT?p=preview Although I am able to retrieve names for the 'classes' object, the selections ...

The data returned from the PHP backend appears to be void

Currently, I am working on a temporary email website and one of the features that I need to incorporate is retrieving the origin of the email which involves accessing the email headers. I have written the following code snippets to achieve this: PHP Backe ...

AngularTS - Using $apply stops the controller from initializing

Every time I launch the application, the angular {{ }} tags remain visible. Removing $scope.$apply eliminates the braces and displays the correct value. I am utilizing Angular with Typescript. Controller: module Application.Controllers { export class Te ...

Angular directive dilemma

Angular is causing some issues for me as I am a beginner in using it. Below is the JSON data that I am dealing with: [ { "name":"43", "values":{ "audio":"Audio Only", "low":"Low Bandwidth", "medium":"Medium Bandw ...

Angular component causing a method to be called before a variable is changed

Currently, I am in the process of refactoring code within an Angular 1.5.8 application to utilize components. (Following similar steps outlined in this guide: ) The basic cases are functioning as expected. However, I have encountered a problem when my co ...

What is the best way to interact with both the child and parent controllers within a directive?

We currently have two directives known as parent and child. Both of these directives come with controllers that house specific functionalities. In the case of the child directive, there are a couple of ways to access controllers: We can access the parent ...

Testing the slider directive using Jasmine unit tests

Here is the code for a slider directive: appCommon.directive('slider', [function () { return { require: 'ngModel', restrict: "A", link: function (scope, element, attr, ngModel) { var mySlider = ...

I am having trouble displaying characters Å, Ä, and Ö in my DDL. Is there a way to instruct restclient to use a particular charset for these characters?

Just before I delve into the issue at hand, let me outline the problem. It should be like this: When it comes to displaying values with characters Å, Ä, and Ö, Björn Nilsson appears as strange special characters. I populate my DDL with data from an A ...

Is there an issue with the initial positioning of the tooltip in the seiyria angular-bootstrap slider?

After implementing the Seiyria angular-bootstrap-slider for a range slider, I encountered an issue where the tooltip is positioned incorrectly upon loading the page. While it functions correctly on a regular page, it appears in the wrong position within a ...

Limitation on calling $http.get() multiple times is in place

Complete Rewriting Of Inquiry The situation has taken a new turn, prompting me to clarify the current scenario from scratch. My goal is to develop a straightforward message board using Node, Express, MongoDB, and Angular. On the server side, my get and ...

Verify the identity of all REST API requests without the need for a username or password in order to obtain a

I have a unique setup where I am selling products. The API fetches product data from a centralized node back-end and displays it on an angular front-end that is hosted on multiple domains. The challenge I'm facing is the need to authenticate all reque ...

Exploring the world of routing parameters in Express.js and AngularJS

Struggling to configure routes with parameters in an AngularJS application supported by a node.js server running on express. The setup involves Node routing all unspecified paths to a catch-all function: app.use(express.bodyParser()); app.use(app.router); ...

Exploring the Power of JQuery and Partial Views within the MVC Framework

This article discusses the topic of Jquery Partial View. You can find more information about it here. I am looking for guidance on how to submit user input values and send them to an ActionResult controller that returns a partial view. -- Below is the co ...

Strange behavior is observed when using ng-view inside ng-controller, especially when refreshing the

Here is the code I am working with: <body ng-controller="CoreCtrl"> <div ng-cloak> <!-- NavBar --> <div ng-include="'/app/core/navbar.html'"></div> <!-- Main content --> <div class="con ...

Click event not triggering on dynamically inserted DIV using jQuery

After the page is rendered in the DOM using jquery, the following code is added: owldata = '<div class="item"><div class="ifl-removepic" ng-click="deleteDocument("'+e.target.result+'");"></div><img src="' + e.targe ...