The preflight request for OPTIONS is receiving a 400 bad request error on the secure HTTPS

When making an Ajax call on the front end and calling a WCF service through Ajax, I encountered an issue with adding headers. As a result, a preflight OPTIONS request is triggered but fails due to the URL being blocked by CORS policy.

I tried adding the following code to my web.config file, but it didn't resolve the issue:

<system.webServer>
        <security>
            <requestFiltering>
                <verbs>
                    <add verb="OPTIONS" allowed="true" />
                    <add verb="POST" allowed="true" />
                    <add verb="GET" allowed="true" />
                    <add verb="DELETE" allowed="false" />
                </verbs>
            </requestFiltering>
        </security>
        <httpProtocol>
            <customHeaders>
                <remove name="X-Powered-By" />
                <add name="Access-Control-Allow-Credentials" value="true" />
                <add name="Access-Control-Allow-Origin" value="*" />
                <add name="Access-Control-Allow-Methods" value="GET,POST,DELETE,OPTIONS" />
                <add name="Access-Control-Allow-Headers" value="accept, cache-control, content-type, authorization, context" />
            </customHeaders>
        </httpProtocol>
    </system.webServer>


$.ajax({
                async: true,
                type: "POST",
                headers: {
                    'Authorization': 'Basic ' + btoa(BasicAuth),
                    'Context': 'Context' + btoa(ContextHeader)
                },
                contentType: "application/json; charset=utf-8",
                data: '{"Id": "' + Id + '" }',
                url: URL + "/MethodName",
                success: function (result) {
                    response = result;
                    if (response == true)
                        Xrm.Page.data.refresh(true);
                    $('#msgDiv').fadeOut('slow');
                },
                error: function (status) {
                    console.log(status.status);
                    $('#msgDiv').fadeOut('slow');
                    Configurations.OnFailure(status);
                }
            });

The above JavaScript code was written to handle the issue.

While it works fine on HTTP calls, HTTPS calls are not successful.

An error message in the console states:

enter code here
  • OPTIONS 400 (Bad Request)

  • Access to XMLHttpRequest at '' from origin 'https://Localhost' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status

Answer №1

Below is a CORS solution that may be helpful for you. Make sure to add the global application class to your WCF service application.
Global.asax

protected void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With,Accept");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }
        }

Web.config on server

< system.serviceModel >
    <bindings>
      <webHttpBinding>
        <binding name="mybinding">
          <security mode="Transport">
            <transport clientCredentialType="Basic" proxyCredentialType="Basic"></transport>
          </security>
        </binding>
      </webHttpBinding>
    </bindings>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
          <dataContractSerializer maxItemsInObjectGraph="2147483647"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior>
          <webHttp />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true">
    </serviceHostingEnvironment>
    <protocolMapping>
      <add scheme="https" binding="webHttpBinding" bindingConfiguration="mybinding"/>
      <add scheme="http" binding="webHttpBinding" />
    </protocolMapping>
  </system.serviceModel>

Remember to install the server service certificate in the client (where you run the JS).
https://i.sstatic.net/C1jTq.png
Javascript Code.

<script>
        function make_base_auth(user, password) {
            var tok = user + ':' + password;
            var hash = window.btoa(tok); //javascript built-in function
            return "Basic " + hash;
        }
        $(function () {
            $.ajax({
                type: "GET",
                url: "https://vabqia130vm:12001/service1.svc/getdata?value=34",
                contentType: "application/json;charset=utf-8",
                beforeSend: function (req) {
                    req.setRequestHeader("Authorization", make_base_auth("administrator",
                        "abcde12345!"));
                },
                success: function (d) {
                    console.log(d);
                },

            });

        })
    </script>

Result:
https://i.sstatic.net/D7mLQ.png
Feel free to reach out if you need further assistance.

Answer №2

I implemented a dispatchmessageInspector on the service side to verify if authentication is correct before calling the actual service.

Here is the code I wrote to handle authentication in the dispatcher inspector:

public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            var logFileName = SetLogInfo("JavaScriptBasicAuth");
            try
            {
                if (!HttpContext.Current.Request.HttpMethod.Equals("OPTIONS"))
                {
                    var basicAuth = HttpContext.Current.Request.Headers["Authorization"];
                    if (basicAuth != null)
                    {
                        string[] separator = basicAuth.Split(' ');
                        BasicAuthenticationBehaviorAttribute basicauth = new BasicAuthenticationBehaviorAttribute();
                        if (!basicauth.ValidateBasicAuth(separator[1]))
                        {
                            throw new WebFaultException(HttpStatusCode.Unauthorized);
                        }
                    }
                    else
                    {
                        FileLogger.LogError("401 (Unauthorized) Error - " + "You are not authorized to perform this operation. Please contact administrator.", LOG_SUB_DIRECTORY, logFileName);
                        throw new WebFaultException(HttpStatusCode.Unauthorized);
                    }
            }
        }

Unfortunately, the call is failing before reaching the Dispatcher inspector code.

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

I encountered an issue with npm run build when attempting to launch a react application on Firebase, resulting in an error

npm ERR! code ENOENT npm ERR! syscall open npm ERR! path C:\Users\Myname\Desktop\god\package.json npm ERR! errno -4058 npm ERR! enoent ENOENT: file 'C:\Users\Myname\Desktop\god\package.json' not f ...

Explain the usage of Razor syntax when defining the name attribute in HTML

Currently, I am utilizing MVC 5 and Razor 3 to dynamically generate an attribute name in HTML using Razor syntax. Specifically, I am focused on creating a data-* attribute. This pertains to determining the name of the attribute rather than its value. Her ...

Rotating Images in 3D with CSS

I am looking for guidance on how to create a rotating image effect on a webpage using CSS/JS. The image should rotate into the plane of the page, similar to the example shown in this post. Can you assist me with this? To better illustrate what I'm tr ...

Determine if the same origin policy is in effect

Is there a method to determine if the same origin policy is applicable to a URL before attempting to use ajax methods? Below is an example of what I currently have: function testSameOrigin(url) { var loc = window.location, a = document.create ...

Is it possible for me to create an If statement that can verify the current index within a Map?

I have the following TypeScript code snippet: export default class SingleNews extends React.Component<INews, {}> { public render(): React.ReactElement<INews> { return ( <> {this.props.featured ...

When attempting to PUT a JSON object to a specific URL, an error occurs

One of my current tasks involves creating a function to send requests to a specific URL function json_object_todo(url, method, param_object, dataObj) { var json_obj; $.support.cors = true; try { var ajax_params = { type: me ...

Using jQuery Datatables: Storing the received JSON data into a variable

I have incorporated 2 plugins for my project: Datatables (used for pagination) Defiant.js (providing JSON search capability) Describing my issue along with the code snippet... $(document).ready(function() { var myjson; //Initializing Datatable ...

Attempting to utilize Ajax to save a file in Laravel, however unsure of what may be causing the issue in my code

Looking for a way to save an image file using ajax in Laravel, here is the code I am currently using: Controller public function store(Request $request) { $item = new Item; // if remove $it_files_path , $it_files_name , $path code work co ...

What is the best way to ensure that my grid remains contained within its designated area?

I need to incorporate a grid of 16x16 or 64x64 into my layout without it overflowing. I'm considering using flexbox, but unsure of the implementation process. My goal is to have the grid resize based on the container size rather than exceeding its bou ...

Click to reveal additional images once the "show more" button is pressed

Hey there! I'm currently working on implementing a feature where, upon clicking "show more", 3 images will be displayed. And if the user clicks again, another set of 3 images will appear, and so on. I seem to be facing some difficulties with the JavaS ...

Tips for effectively creating a fresh array of objects by extracting distinct values from arrays of child elements within a collection of parent objects

We have a requirement to extract data from objects structured like this: [ { "first": { "children" : [{ "name": "abc", "detail":"123"}, { "name": "def", "detail":"456"} ] }}, { "second": { "children" : [{ ...

Guide to Including an Object in AngularJS Scope

I am completely new to Angular JS and mongod. My goal is to add a new ingredient field to this page for the specific drink that the + button is clicked on. Here is how my view looks like: UI Image This is what my .jade file contains: block content ...

Using AJAX to submit a form with a file to Symfony results in $form->isValid returning false

Utilizing Angular JS code, I employ a method to submit a file and additional fields (along with a CSRF token) to a Symfony controller. var formObject = new FormData; formObject.append('email', self.careers[index].application.email); formO ...

Cloning a repository does not support Typescript compilation

After creating an Angular2 component, I wanted to share the code with my colleagues. Therefore, I uploaded the code to Github, cloned the repository, ran npm install, and then npm run tsc. However, I encountered the following errors: error TS2318: Cannot ...

TypeOrm is struggling to identify the entities based on the directory path provided

Currently, I am utilizing TypeORM with NestJS and PostgreSql to load entities via the datasource options object. This object is passed in the useFactory async function within the TypeORM module as shown below: @Module({ imports: [TypeOrmModule.forRootAsy ...

The polygon array feature is not functioning as expected in the Google Maps API

I'm currently facing an issue with a code that is supposed to draw polygons from an array in the Google Maps API, but unfortunately, it doesn't seem to be working as expected. <!DOCTYPE html> <html> <head> <script src ...

Inspecting a substring of an element dynamically added in VueJs

When I click a button in my form, it adds a new line. The challenge is making sure that each new line evaluates independently and correctly. In this case, the task involves checking the first 2 digits of a barcode against a dataset to determine a match or ...

Encode a file (such as an image) using ajax and execute an insertion query

Seeking advice on integrating a file (image) using AJAX. Utilizing serialization to gather form data and populate it into my table, I am eager to implement AJAX on my website to enhance user experience without refreshing. My ongoing learning journey involv ...

What is the best way to include an external JavaScript file in a Bootstrap project?

I am brand new to front-end development and I'm attempting to create an onClick() function for an element. However, it seems like the js file where the function is located is not being imported properly. I've tried following some instructions to ...

Using AngularJS ng-model to select options in a dropdown menu with WebDriver

In the following code snippet, an AngularJS based dropdown menu is implemented: <select _ngcontent-c1="" class="form-control ng-pristine ng-valid ng-touched"> After opening the list, I attempted to select a variable from this list using the code be ...