Having trouble deciphering the request header value within the REST web API

Utilizing Ajax, I am storing the token in the request header and sending it to a Rest API. Here is the request sent to the web API:


var xhr = new XMLHttpRequest();
$.ajax({
    url: 'http://localhost:32253/api/UserDetail/Authenticate',
    headers: {
        "Authorization-Token": res,
        "X-HTTP-Method-Override": "GET"
    },
    type: 'GET',
    async: false,
    contentType: "application/json",
    dataType: 'json',
    success: function (data) {
        alert("Success from success callback!");
        // ShowData(data);                    
        $('#RId').text(data.RoleId);
        $('#RDesc').text(data.RoleDescription);
        $('#RName').text(data.RoleName);
    },
    error: function (xhr, status) {
        alert(status);
    }
});

When attempting to read the header on the server-side (Rest API), I encounter an issue.


if (Request.Headers.Contains("Authorization-Token")) {
    var token = Request.Headers.GetValues("Authorization-Token").First();
}

However, the request does not contain the "Authorization-Token" header. After enabling CORS, I noticed the header name in Access-Control-request-Headers but struggled to determine how to read its value. Any assistance would be greatly appreciated.

UPDATE: I have now opted to pass the token using the standard Authorization header of the request object.


$.ajax({
    url: 'http://localhost:32253/api/UserDetail/Authenticate',
    beforeSend: function (xhr) {
        xhr.setRequestHeader("Authorization", "Basic " + res);
    },
    type: 'GET',
    async: false,
    contentType: "application/json",
    dataType: 'json',
    authorization: res,
    success: function (data) {
        alert("Success from success callback!");
        // ShowData(data);                    
        $('#RId').text(data.RoleId);
        $('#RDesc').text(data.RoleDescription);
        $('#RName').text(data.RoleName);
    },
    error: function (xhr, status) {
        alert(status);
    }
});

Despite this change, I am unable to locate the token in the request headers. For more information, please refer to the image below:

REQUEST LOG: Here is the request received at the server side:


OPTIONS /api/UserDetail/Authenticate HTTP/1.1
Connection: keep-alive
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding: gzip, deflate
Accept-Language: en-GB,en;q=0.5
Host: localhost:32253
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0
Access-Control-Request-Method: GET
Access-Control-Request-Headers: authorization-token,content-type
Origin: http://localhost:14576

Answer №1

Stick to standard header names to ensure the value is passed through all network hops. Use the Authorization header with a Bearer scheme, as it is standard practice. In C#, this header is also a standard property.

"Authorization" : "Bearer sometoken"

var header = this.Request.Headers.Authorization;
if(header != null && header.Scheme == "Bearer") { /* do something with header.Value */ }

If using a non-standard header is necessary, prefix it with X, for example:

"X-Authorization-Token" : "sometoken"

X-headers should not encounter issues with proxies or routers.

UPDATE

Consider setting the headers using the beforeSend option:

beforeSend: function (xhr) {
    xhr.setRequestHeader('Authorization-Token', res);
},

Answer №2

Try this method:

let request = new XMLHttpRequest();
        $.ajax({
            url: 'http://localhost:32253/api/UserDetail/Authenticate',
            beforeSend: function (request) { 
                request.setRequestHeader('Authorization-Token', response);
                request.setRequestHeader('X-HTTP-Method-Override', "GET");
            },
            type: 'GET',
            async: false,
            contentType: "application/json",
            dataType: 'json',
            success: function (data) {
                alert("Success from success callback!");
                // ShowData(data);                    
                $('#RId').text(data.RoleId);
                $('#RDesc').text(data.RoleDescription);
                $('#RName').text(data.RoleName);
            },
            error: function (request, status) {
                alert(status);
            }
            //complete: function (data) {
            //    alert("Success!from complete function");
            // } 
        });

UPDATE: I managed to capture the network traffic and extract tokens from the request headers. Refer to the image for more information

https://i.sstatic.net/qA86U.png

It's hard to provide a complete solution without seeing the full code.

Answer №3

Appreciate your input, Daniel. The problem was indeed related to the OPTIONS Request as you mentioned. I made sure to set the Access-Control-Allow-Headers in the response for OPTIONS request. Below is the snippet I added in the global.asax.cs file of the REST Web API:

protected void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost:14576");
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");

                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Authorization-Token, X-HTTP-Method-Override");
                HttpContext.Current.Response.End();
            }
        }

On the client side, the request code looks like this:

 var xhr = new XMLHttpRequest();
            $.ajax({
                url: 'http://localhost:32253/api/UserDetail/Authenticate',
                beforeSend: function (xhr) {
                    xhr.setRequestHeader('X-Authorization-Token', res);
                    xhr.setRequestHeader('X-HTTP-Method-Override', "GET");
                },
                type: 'GET',
                async: false,
                dataType: 'json',
                success: function (data) {
                    alert("Success from success callback!");
                },
                error: function (xhr, status) {
                    alert(status);
                }
            });

The code in the REST web API for reading the header is as below:

if (Request.Headers.Contains("X-Authorization-Token"))
            {

                var token = Request.Headers.GetValues("X-Authorization-Token").First();
}

Everything is now working smoothly. Big thanks to all for your time and valuable suggestions :)

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

The code in check.js causes a square of dots to emerge on the screen in Skype

Trying to add a Skype call button to my page has been successful, but there's one issue - a pesky white dot keeps appearing at the bottom of the footer. The script source I used is as follows: <script src="http://download.skype.com/share/skypebu ...

Timeout occurred while acquiring a turn-based concurrency lock for the actor '{actorName}' after {time}

My service is responsible for creating Actors of a certain type with specific names: var storer = this.serviceClient.Create<IStorer>(new ActorId(agencyToProcess.Name)); After creating the Actor, I then call a method within it: await storer.StoreSt ...

Guidance on Implementing a Delay and FadeIn Effect for AJAX Responses from JSON Iterator

How can I iterate over the following foreach loop with a delay between each item and a fadeIn effect on each? I am debating whether .append() is the most suitable function to use since I want to load a templated div with the class #fan for each person in ...

What is the process for applying a border to the chosen image within the ImageList of the MaterialUI component?

Currently, I have set up the images in a grid format using the and components from MaterialUI. However, I am looking to implement an additional feature where when a user clicks on a specific image from the grid, a border is displayed around that select ...

Once logged out in Vue Router, the main app template will briefly display along with the login component

After clicking the logout button, I am experiencing an issue where my main UI remains visible for a few seconds before transitioning to a blank page and displaying the login form component. This behavior is occurring within the setup of my App.vue file: & ...

Hello there! Can you assist me in converting data from {"rOjbectId":["abc","def","ghi","ghikk"]} to ["abc", "def", "ghi", "ghikk"] through the use of ajax?

I need assistance with converting data from {"rOjbectId":["abc","def",ghi","ghikk"]} to "["abc", "def", "ghi", "ghikk"] using ajax. Can someone please guide me through this process? ...

How to showcase an image with Angular 2?

Just starting out with Angular 2 and ran into an issue while trying to display an image using a relative path. <img src="./../images/publicVideo1.PNG"> Unfortunately, I encountered the following error: null:1 GET http://localhost:4200/null 404 (No ...

Stop the print dialog box from causing the page to refresh

I have implemented a print button for an invoice: </script> <!--Function for printing invoice--> <script> function printpage() { window.print() } </script> <button id="print" name="print" class="btn btn-info" onClick="pri ...

Can hash routes be defined in next.js?

Previously, I created a modal component using <HashRouter> in react-router where the modal would become active or inactive based on the hash url. For example, the modal is inactive when the url is /route, but becomes active when the url is /route#m ...

Executing an AJAX Request in ASP.NET

I am trying to execute a JQuery Ajax call in asp.net. I have set up my WebMethod to return a String, but when the ajax call is successful, instead of just getting the string result, I receive the complete HTML of the page. I have even tried setting type: " ...

Time picker in Bootstrap - Ensuring end time is not earlier than start time validation

How to prevent users from selecting a past time for the end time in Bootstrap time picker with start time validation <html> <head> </head> <body> <link href="https://maxcdn.bootst ...

Switching up the content of an HTML page with JavaScript or JQuery: what you need

Is it possible to update HTML content using JavaScript or JQuery? https://i.sstatic.net/EWOXg.png I am trying to change the contents from 1 to 5 in a sequential order based on the time shown in the image. How can I achieve this using JavaScript or JQuery ...

Is there a sweet TypeScript class constructor that can take in its own instance as an argument?

I have a scenario where I need to read in instances of Todo from a CSV file. The issue is that Papaparse does not handle dynamic conversion on dates, so I'm currently dropping the object into its own constructor to do the conversion: class Todo { ...

How can I create a custom Sweet Alert button in JavaScript that redirects to a specific webpage when clicked?

Here's what I have in my code: swal({ title: 'Successfully Registered!', text: "Would you like to proceed to the Log In page?", type: 'success', showCancelButton: true, confirmButtonColor: '#308 ...

step-by-step guide on transferring the text content of an HTML paragraph element to another HTML paragraph element through JavaScript in ASP.NET

I'm looking for help with passing the text value from one HTML paragraph element to another when a JavaScript function is called. The function loads a div element with an enlarged image and a paragraph content. Below is the code I am using: JavaScrip ...

ERROR: JSON parsing failed due to an unexpected token "<", indicating an issue with the syntax and structure of the input data

Currently, I am following a tutorial on Scrimba to learn about React and React Router 6. Unfortunately, I have encountered an error with the data provided in the tutorial. The error message reads as follows: 67:1 Uncaught (in promise) SyntaxError: Unexpect ...

Dealing with distinct values in structured data input

Greetings to everyone. Situation Overview In my project, I have a model called resumeSkills which stores the resume ID, skill ID from different tables, and a field for "proficiency level" to indicate the expertise level in that specific skill. https://i ...

Redirect to the last folder with an ASP.NET 301 redirection

I have a task to create a 301 redirect for all previous links that include (/CID-VALUE), such as www.example.com/folder1/folder2/CID-1234. These links may have been located in any folder, so I need a solution that captures all occurrences of CID- along wit ...

A guide to generating a user-specific log file in ASP.NET by leveraging session data and log4net

I have recently set up logging using log4net and successfully created a log file to store information. However, I am now faced with the task of implementing user profiles and generating log files based on the user with a specific format [AID_YYYYMMDD]. C ...

Please confirm the modal by adding a textarea with a newline in SweetAlert2

Every time I attempt to add a line break in the textarea input field, the modal pops up. I have tried adding these lines of code as well, but nothing seems to be working: allowEnterKey: false, focusConfirm: false, Does anyone have any advice for solving ...