title: CORS in Ajax-requests against an MVC controller with IdentityServer3-authorization
body: <p>I'm currently working on site that uses various Ajax-requests to save, load and autocomplete data. It is build using C#, MVC and JQuery. All actions on the MVC controllers require the users to be authorized, and we use IdentityServer3 for authentication. It was installed using NuGet, and the current version is 2.3.0.</p>
  
  <p>When I open the page and push buttons, everything is working just fine. The problem seem to occur when a certain session expires. If I stay idle for a while, and try to use an Ajax-function, it generates the following error:</p>
  
  <blockquote>
    <p>XMLHttpRequest cannot load <a href="https://identityserver.domain.com/connect/authorize?client_id=Bar&amp;redirect_uri=http%3a%2f%2flocalhost%3a12345&amp;response_mode=form_post&amp;response_type=id_token+token&amp;scope=openid+profile+email+phone+roles" rel="nofollow noreferrer">https://identityserver.domain.com/connect/authorize?client_id=Bar&amp;redirect_uri=http%3a%2f%2flocalhost%3a12345&amp;response_mode=form_post&amp;response_type=id_token+token&amp;scope=openid+profile+email+phone+roles</a> [...]. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '<a href="http://localhost:12345" rel="nofollow noreferrer">http://localhost:12345</a>' is therefore not allowed access.</p>
  </blockquote>
  
  <p>From what I know about Ajax, the problem itself is pretty simple. The MVC site has lost track of the current session, and it is asking the client to authenticate again. The response I get from the Ajax-request is a "302 Found", with a Location-header that points to our IdentityServer. The IdentityServer happens to be on another domain, and while this works fine when you are performing regular HTTP-requests, it does not work particularly well for Ajax-requests. The "Same Origin Policy" is straight up blocking the Ajax-function from authenticating. If I refresh the page, I will be redirected to the IdentityServer and authenticate normally. Things will then go back to normal for a few minutes.</p>
  
  <p>The solution is probably to add an extra header in the response message from the IdentityServer, that explicitly states that cross-origin requests are allowed for this service.</p>
  
  <p>I am currently <strong>not</strong> getting this header from the IdentityServer (checked in Fiddler).</p>
  
  <p><a href="https://identityserver.github.io/Documentation/docs/configuration/cors.html" rel="nofollow noreferrer">According to the docs</a>, it should be enabled by default. I have checked that we have indeed enabled CORS this way:</p>
  
  <pre><code>factory.CorsPolicyService = new Registration&lt;ICorsPolicyService&gt;(new DefaultCorsPolicyService { AllowAll = true });
  </code></pre>
  
  <p>This is one of my clients:</p>
  
  <pre><code>new Client
  {
      Enabled = true,
      ClientName = "Foo",
      ClientId = "Bar",
      ClientSecrets = new List&lt;Secret&gt;
      {
          new Secret("Cosmic")
      },
      Flow = Flows.Implicit,
      RequireConsent = false,
      AllowRememberConsent = true,
      AccessTokenType = AccessTokenType.Jwt,
      PostLogoutRedirectUris = new List&lt;string&gt;
      {
          "http://localhost:12345/",
          "https://my.domain.com"
      },
      RedirectUris = new List&lt;string&gt;
      {
          "http://localhost:12345/",
          "https://my.domain.com"
      },
      AllowAccessToAllScopes = true
  }
  </code></pre>
  
  <p>These settings do not work. I am noticing that I have an extra forward slash in the URIs here, but if I remove them, I get the default IdentityServer-error that states that the client is not authorized (wrong URI). If I deploy the site (instead of running a localhost debug), I use the domain name without a trailing slash, and I get the exact same behaviour as I do in debug. I do notice that there is no trailing slash in the error message above, and I figured this could be the problem until I saw the same thing in the deployed version of the site.</p>
  
  <p>I also made my own policy provider, like this:</p>
  
  <pre><code>public class MyCorsPolicyService : ICorsPolicyService
  {
      public Task&lt;bool&gt; IsOriginAllowedAsync(string origin)
      {
          return Task.FromResult(true);
      }
  }
  </code></pre>
  
  <p>... and I plugged it into the IdentityServerServiceFactory like this:</p>
  
  <pre><code>factory.CorsPolicyService = new Registration&lt;ICorsPolicyService&gt;(new MyCorsPolicyService());
  </code></pre>
  
  <p>The idea is for it to return true regardless of origin. This did not work either; exactly the same results as before.</p>
  
  <p>I've read about a dozen other threads on this particular subject, but I'm getting nowhere. To my knowledge, we are not doing anything unusual when it comes to the setup of the different sites. It's all pretty much out-of-the-box. Any advice?</p>
  
  <h1>----- UPDATE -----</h1>
  
  <p>The problem persists. I have now tried some fresh tactics. I read somewhere that cookie authentication was bad for Ajax-requests, and that I should be using bearer tokens instead. I set this up in Ajax like this:</p>
  
  <pre><code>$(function () {
      $(document).ajaxSend(function (event, request, settings) {
          console.log("Setting bearer token.");
          request.setRequestHeader("Authorization", "Bearer " + $bearerToken);
      });
  });
  </code></pre>
  
  <p>Both the console in Chrome and Fiddler confirms that the token is indeed present and sent by JQuery. The token I use comes from the access_token-property on claims principal object from HttpContext.GetOwinContext().Authentication.User.</p>
  
  <p>This didn't do much. I still get a 302-response from the server, and Fiddler reveals that the token is not sent on the following Ajax-request (which is a GET-request) to the IdentityServer.</p>
  
  <p>From there, I read this thread:
  <a href="https://stackoverflow.com/questions/13624386/handling-cors-preflight-requests-to-asp-net-mvc-actions">Handling CORS Preflight requests to ASP.NET MVC actions</a>
  I tried to put this code in to the startup.cs of the IdentityServer, but there does not appear to be a "preflight" request going in. All I see in Fiddler is this (from the beginning):</p>
  
  <h1>1 - The initial Ajax-request from the client to the MVC controller:</h1>
  
  <pre><code>POST http://localhost:12345/my/url HTTP/1.1
  Host: localhost:12345
  Connection: keep-alive
  Content-Length: pretty long
  Authorization: Bearer &lt;insert long token here&gt;
  Origin: http://localhost:12345
  User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36
  Content-Type: application/x-www-form-urlencoded; charset=UTF-8
  Accept: application/json, text/javascript, */*; q=0.01
  X-Requested-With: XMLHttpRequest
  Referer: http://localhost:12345/my/url
  Accept-Encoding: gzip, deflate
  Accept-Language: nb-NO,nb;q=0.8,no;q=0.6,nn;q=0.4,en-US;q=0.2,en;q=0.2
  Cookie: OpenIdConnect.nonce.&lt;insert 30 000 lbs of hashed text here&gt;
  
  param=fish&amp;morestuff=salmon&amp;crossDomain=true
  </code></pre>
  
  <h1>2 - The redirect response from the MVC controller:</h1>
  
  <pre><code>HTTP/1.1 302 Found
  Cache-Control: private
  Location: https://identityserver.domain.com/connect/authorize?client_id=Bar&amp;redirect_uri=http%3a%2f%2flocalhost%3a12345%2f&amp;response_mode=form_post&amp;response_type=id_token+token&amp;scope=openid+profile+email [...]
  Server: Microsoft-IIS/10.0
  X-AspNetMvc-Version: 5.2
  X-AspNet-Version: 4.0.30319
  Set-Cookie: OpenIdConnect.nonce.&lt;lots of hashed text&gt;
  X-SourceFiles: &lt;more hashed text&gt;
  X-Powered-By: ASP.NET
  Date: Fri, 15 Jan 2016 12:23:08 GMT
  Content-Length: 0
  </code></pre>
  
  <h1>3 - The Ajax-request to the IdentityServer:</h1>
  
  <pre><code>GET https://identityserver.domain.com/connect/authorize?client_id=Bar&amp;redirect_uri=http%3a%2f%2flocalhost%3a12345%2f&amp;response_mode=form_post&amp;response_type=id_token+token&amp;scope=openid+profile+email [...]
  Host: identityserver.domain.com
  Connection: keep-alive
  Accept: application/json, text/javascript, */*; q=0.01
  Origin: http://localhost:12345
  User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36
  Content-Type: application/x-www-form-urlencoded; charset=UTF-8
  Referer: http://localhost:12345/my/url
  Accept-Encoding: gzip, deflate, sdch
  Accept-Language: nb-NO,nb;q=0.8,no;q=0.6,nn;q=0.4,en-US;q=0.2,en;q=0.2
  </code></pre>
  
  <h1>4 - The response from IdentityServer3</h1>
  
  <pre><code>HTTP/1.1 302 Found
  Content-Length: 0
  Location: https://identityserver.domain.com/login?signin=&lt;some hexadecimal id&gt;
  Server: Microsoft-IIS/8.5
  Set-Cookie: SignInMessage.&lt;many, many, many hashed bytes&gt;; path=/; secure; HttpOnly
  X-Powered-By: ASP.NET
  Date: Fri, 15 Jan 2016 12:23:11 GMT
  </code></pre>
  
  <h1>5 - The meltdown of Chrome</h1>
  
  <blockquote>
    <p>XMLHttpRequest cannot load <a href="https://identityserver.domain.com/connect/authorize?client_id=Bar&amp;blahblahblah" rel="nofollow noreferrer">https://identityserver.domain.com/connect/authorize?client_id=Bar&amp;blahblahblah</a>. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '<a href="http://localhost:12345" rel="nofollow noreferrer">http://localhost:12345</a>' is therefore not allowed access.</p>
  </blockquote>