0

I have a simple ASP.NET Web API application with individual accounts for authentication.

I enabled CORS in it: installed package and added:

var cors = new EnableCorsAttribute(
        origins: "*",
        headers: "*",
        methods: "*");
        config.EnableCors(cors);

to the file WebApiConfig.

Now, I want to make requests from a simple web page using jQuery. I have this code now:

var loginData = {
    grant_type: "password",
    username: "foo",
    password: "Something_1562"
};

$.ajax({
    type: 'POST',
    url: "https://localhost:44351/Token",
    data: loginData
}).done(function (data) {
    alert(data.userName);
    alert(data.access_token);

}).fail(function (data) {
    alert('Request Status: ' + req.status + ' Status Text: ' + req.statusText + ' ' + req.responseText);
});

And I get this:

XMLHttpRequest cannot load https://localhost:44351/Token. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

EDIT:

Some extra information: - I have https/ssl enable on the web api - The API is running on ISS Express

ekad
  • 14,436
  • 26
  • 44
  • 46

1 Answers1

1

I hope these following couple of points & links are useful:

Access-Control-Allow-Origin: * 

The value of "*" is special in that it does not allow requests to supply credentials, meaning HTTP authentication, client-side SSL certificates, nor does it allow cookies to be sent. Source: Wikipedia

Therefore your Web API needs to specify which URL is accessing it using AJAX. For example.

[EnableCors(origins: "http://yourAjaxClientURL", headers: "*", 
    methods: "*", SupportsCredentials = true)]

To allow cross-origin credentials in Web API, set the SupportsCredentials property to true on the [EnableCors] attribute. Source: Enabling Cross-Origin Requests in ASP.NET Web API 2

Third useful link www.w3.org - cors

jyrkim
  • 2,849
  • 1
  • 24
  • 33
  • Btw, I'm now having a different problem: my GET requests are being changed to OPTIONS which results on a 405 code. I have read some posts but nothing works... Any tips? – Cátia Azevedo Dec 11 '16 at 21:17
  • @CátiaAzevedo Also maybe these links are helpful too: http://enable-cors.org/server_iis7.html and http://stackoverflow.com/questions/28488535/cors-settings-for-iis-7-5 – jyrkim Dec 12 '16 at 07:09
  • @CátiaAzevedo if the new problem exists, then it might worthwhile to create a new question. I'm not familiar with the "GET requests are being changed to OPTIONS" message - sorry – jyrkim Dec 12 '16 at 08:32