0

I have an MVC app that I've developed with an Azure AD login. I'm using ajax to call a function in my controller that writes to a database, however, I'm getting this error thrown:

https://login.microsoftonline.com/{XXX}.onmicrosoft.com/wsfed?w…%3d0%26id%3dpassive%26ru%3d%252fHome%252fpost&wct=2016-11-04T19%3a37%3a05Z. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://mysite.mysite.ca' is therefore not allowed access.

here's the ajax call that's throwing the error:

 $.ajax({
    type: "POST",
    url: "Home/post",
    data: item,
    dataType: "json"
    success: KPR.showNewApp(item),
    error: function (xhr, ajaxOptions, thrownError) {
       console.log(xhr);
       console.log(thrownError);
    }
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Kevin Kulla
  • 460
  • 3
  • 20
  • 1
    The error means that there are no CORS headers present in the response of your cross domain request. See [this question](http://stackoverflow.com/questions/3595515/xmlhttprequest-error-origin-null-is-not-allowed-by-access-control-allow-origin?rq=1) for more details. I'm confused as to how you request to `home/post` is getting forwarded on (via JS) to `login.microsoft.com`, though. – Rory McCrossan Nov 04 '16 at 20:03
  • I figured it was because of the CORS header, but yeah, I'm confused about that too. The only thing I can think of is because my login token expired and it needs to reauthorize and it's trying to do it. – Kevin Kulla Nov 04 '16 at 20:10

1 Answers1

0

how you request to home/post is getting forwarded on (via JS) to login.microsoft.com

As I know, the function in the controller need authorization when you add attribute([Authorize]) in the controller. If you want to use ajax, you will encounter CORS issue. I would suggest you cache the token and add token to its header when you use ajax like the following:

$.ajax({
type: "POST",
headers: {
  "Authorization": "bearer " + token
},
url: "Home/post",
data: item,
dataType: "json"
success: KPR.showNewApp(item),
error: function (xhr, ajaxOptions, thrownError) {
   console.log(xhr);
   console.log(thrownError);
}
});
Jambor - MSFT
  • 3,175
  • 1
  • 13
  • 16
  • Which token should I be caching? Is it my cookie FedAuth=...? – Kevin Kulla Nov 08 '16 at 14:04
  • Also, not sure if this changes anything but I can call the Ajax when I refresh the page or after I log in, it's only after a period of time that I get this error. – Kevin Kulla Nov 08 '16 at 15:17
  • From my experience, I think you write authentication code in your mvc code behind. What I mean is to store the token in cache or some other storage. When use ajax function add this token to the header. – Jambor - MSFT Nov 10 '16 at 06:04