Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9188671
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T20:04:13+00:00 2026-06-17T20:04:13+00:00

Background I have CORS working in my local dev environment when authentication (JWT) succeeds.

  • 0

Background

I have CORS working in my local dev environment when authentication (JWT) succeeds. I have the client page running off of localhost and calling into api.mycompany.com for data.
My api project checks for a valid JWT, and if it passes, returns the content. It took me a while to get here, but this all works fine.

If I do not send a valid JWT, the api responds properly with a 401 (checked this in Fiddler), but the error function callback on the client reports an error code of 0 and a status of “error”.

I want the ajax callback function to check the status code of the error and if it is 401, check the headers for a header named location (which will contain the uri to the authentication service).

Setup

  • (API Project) Visual Studio 2012 instance running MVC4 project on local IIS Express

    • Local host file maps 127.0.0.1 to api.mycompany.com
    • Set Project -> Properties -> Web to IIS Express
      • Use Local IIS Express (checked)
      • Project Url: http://localhost:8080
      • Created Virtual Directory
      • Override application root URL (checked)
      • Override application root URL: http://api.mycompany.com:8080
    • In applicationhost.config under sites:

      <site name="StuffManagerAPI" id="1">
        <application path="/" applicationPool="Clr4IntegratedAppPool">
          <virtualDirectory path="/" physicalPath="C:\Users\me\Documents\Visual Studio 2012\Projects\StuffManagerAPI\StuffManagerAPI" />
        </application>
        <bindings>
          <binding protocol="http" bindingInformation="*:8080:localhost" />
          <binding protocol="http" bindingInformation="*:8080:api.mycompany.com" />
        </bindings>
      </site>
      
  • (Client Project) Separate Visual Studio Instance with ASP.net empty web application

    • Set Project -> Properties -> Web to IIS Express
      • Use Local IIS Express (checked)
      • Project Url: http://localhost:22628
      • Created Virtual Directory
  • Using Google Chrome as the test client

  • Using Fiddler to view traffic

Code

I think these should be the important bits from my Proof of Concept. Once again, the CORS preflight and data retrieval all work fine. It’s just the unauthorized case that is not working. If you need anything else, please let me know. Thanks for the help.

API Project

Authorization Header Handler

using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;

namespace StuffManagerAPI.Handlers
{
public class AuthorizationHeaderHandler : DelegatingHandler
{
    private const string KEY = "theKey";

    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
    {
        var taskCompletionSource = new TaskCompletionSource<HttpResponseMessage>();

        const string identityProviderUri = "https://idp.mycompany.com";

        IEnumerable<string> apiKeyHeaderValues = null;
        if (request.Headers.TryGetValues("Authorization", out apiKeyHeaderValues))
        {
            var apiKeyHeaderValue = apiKeyHeaderValues.First();
            var token = apiKeyHeaderValue.Split(' ').LastOrDefault();
            var tokenProcessor = new JasonWebTokenDecryptor.JasonWebToken(token, KEY);

            if (tokenProcessor.IsValid)
            {
                base.SendAsync(request, cancellationToken).ContinueWith(t => taskCompletionSource.SetResult(t.Result));
            }
            else
            {
                var response = FailedResponseWithAddressToIdentityProvider(identityProviderUri);
                taskCompletionSource.SetResult(response);
            }

        }
        else
        {
            if(request.Method.Method != "OPTIONS")
            {
                //No Authorization Header therefore needs to redirect
                var response = FailedResponseWithAddressToIdentityProvider(identityProviderUri);
                taskCompletionSource.SetResult(response);
            }
            else
            {
                base.SendAsync(request, cancellationToken).ContinueWith(t => taskCompletionSource.SetResult(t.Result));
            }
        }

        return taskCompletionSource.Task;
    }

    private static HttpResponseMessage FailedResponseWithAddressToIdentityProvider(string identityProviderUri)
    {
        // Create the response.
        var response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
        response.Headers.Add("Location", identityProviderUri);
        return response;
    }
}
}

Stuff Controller

using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Http;
using StuffManagerAPI.Attributes;
using StuffManagerAPI.Models;

namespace StuffManagerAPI.Controllers
{
[HttpHeader("Access-Control-Allow-Origin", "*")]
[HttpHeader("Access-Control-Allow-Methods", "OPTIONS, HEAD, GET, POST, PUT, DELETE")]
[HttpHeader("Access-Control-Allow-Headers", "Authorization")]
[HttpHeader("Access-Control-Expose-Headers", "Location")]
public class StuffController : ApiController
{
    private readonly Stuff[] _stuff = new[]
        {
            new Stuff
                {
                    Id = "123456",
                    SerialNumber = "112233",
                    Description = "Cool Item"
                },
            new Stuff
                {
                    Id = "456789",
                    SerialNumber = "445566",
                    Description = "Another Cool Item"
                }
        };

    public Stuff Get(string id)
    {
        var item = _stuff.FirstOrDefault(p => p.Id == id);
        if (item == null)
        {
            throw new HttpResponseException(HttpStatusCode.NotFound);
        }

        return item;
    }

    public IEnumerable<Stuff> GetAll()
    {
        return _stuff;
    }

    public void Options()
    {
       // nothing....
    }

}
}

Client Project

main.html

<!DOCTYPE html>
<html lang="en">
<head>
    <title>ASP.NET Web API</title>
    <link href="../Content/Site.css" rel="stylesheet" />
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.js"></script>

    <script type="text/javascript">
        var baseUrl = "http://api.mycompany.com:8080/api/";
        $.support.cors = true;

        $(document).ready(
            getListofStuff()
        );

        function setHeader(xhr) {
            xhr.setRequestHeader('authorization', 'Bearer blah.blah.blah');
        }

        function getListofStuff() {
            var apiUrl = baseUrl + "stuff/";

            $.ajax({
                url: apiUrl,
                type: 'GET',
                dataType: 'json',
                crossDomain: true,
                success: receivedListOfStuff,
                error: receiveError,
                beforeSend: setHeader,
                statusCode: {
                    0: function() {
                        alert('got 0');
                    },
                    401: function () {
                        alert('finally got a 401');
                    }
                }
            });
        }

        function getIndividualPieceOfStuff(id) {
            var apiUrl = baseUrl + "stuff/" + id;

            $.ajax({
                url: apiUrl,
                type: 'GET',
                dataType: 'json',
                crossDomain: true,
                success: receivedIndividualStuffItem,
                error: receiveError,
                beforeSend: setHeader
            });
        }

        function receivedListOfStuff(data) {
            $.each(data, function (key, val) {

                var listItem = $('<li/>').text(val.Description);
                listItem.data("content", { id: val.Id});
                $(".myStuff").prepend(listItem);
            });

            $(".myStuff li").click(function () {
                getIndividualPieceOfStuff($(this).data("content").id);
            });
        }

        function receivedIndividualStuffItem(data) {
            $("#stuffDetails #id").val(data.Id);
            $("#stuffDetails #serialNumber").val(data.SerialNumber);
            $("#stuffDetails #description").val(data.Description);
        }

        function receiveError(xhr, textStatus, errorThrown) {
            var x = xhr.getResponseHeader("Location");
            var z = xhr.responseText;

            if (xhr.status == 401){
                alert('finally got a 401');
               }

            alert('Error AJAX');
        }
    </script>

</head>
<body>
.
.
.
.
</body>
</html>
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T20:04:15+00:00Added an answer on June 17, 2026 at 8:04 pm

    I finally figured it out. In the Authorization Header Handler, when tokenProcessor.IsValid is false, I jump to FailedResponseWithAddressToIdentityProvider and then immediately set the result and mark the task as complete. Therefore, I never visit the Stuff Controller and get the Access Control Headers added:

    if (tokenProcessor.IsValid)
    {
        base.SendAsync(request, cancellationToken).ContinueWith(t => taskCompletionSource.SetResult(t.Result));
    }
    else
    {
        var response = FailedResponseWithAddressToIdentityProvider(identityProviderUri);
                taskCompletionSource.SetResult(response);
    }
    .
    .
    .
    private static HttpResponseMessage FailedResponseWithAddressToIdentityProvider(string identityProviderUri)
    {
        // Create the response.
        var response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
        response.Headers.Add("Location", identityProviderUri);
        return response;
    }
    

    }

    There is probably a better way to do this, but I simply added the headers to my response in the FailedResponseWithAddressToIdentityProvider method and the browser finally sees the 401 in Chrome, Firefox, and IE8. Here is the change:

    private static HttpResponseMessage FailedResponseWithAddressToIdentityProvider(string identityProviderUri)
    {
        // Create the response.
        var response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
        response.Headers.Add("Location", identityProviderUri);
        response.Headers.Add("Access-Control-Allow-Origin", "*");
        response.Headers.Add("Access-Control-Allow-Methods", "OPTIONS, HEAD, GET, POST, PUT, DELETE");
        response.Headers.Add("Access-Control-Allow-Headers", "Authorization");
        response.Headers.Add("Access-Control-Expose-Headers", "Location");
        return response;
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Background: We have a Webservice that is running under axis2 on a Tomcat. We
Background I have a custom authentication back end for our django applications that refers
Background: I have an ASP.NET MVC view page with a MultiSelectList in the View
Background : I have a .Net 3.5 WPF Prism-based application running on Windows XP
Background I have a form that PHP generates from my database. The page is
Background I have been asked by a client to create a picture of the
Background: We have an offshore group working up a Silverlight 2 prototype for us.
Background: I have an MVC based polaroid object. The model keeps the photo's metadata,
Background I have an array of objects (Users) defined and set as follows: //
Background I have two lists, the first is items which contains around 250 tuples,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.