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

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

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á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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.