1

I need to use my company's authentication service, which runs on a remote server. I've been trying to do an ajax call to the service(API) using jquery AJAX as follows....

var uri = "http://Company/Authentication/AuthAPI";
            $.ajax(uri, {
                type: "POST",
                data: JSON.stringify(user),
                contentType: "application/json",
                success: function () {
                    //here reload the page so that the new vacancy will be showed
                    alert("logged in");
                }
            });

I get this error in my chrome console...

No 'Access-Control-Allow-Origin' header is present on the requested resource,

I went through this, and this, and got to know that I have to set Access-Control-Allow-Origin header on the server side to * or set it to my domain.

Now, the actual question is when I hit the same authentication service using fidler everything seems to work just fine, this is driving me crazy guys, please enlighten me

EDIT: And somehow this seems to work with .NET MVC Code too...

public UserData AuthenticateUser(User userDetails)
    {
        try
        {
            using (var _client = new HttpClient())
            {
                var result = new UserData();
                _client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                string subUri = Utilities.GetConfigValueFromSection(ConfigurationConstants.AuthenticationServiceSection, ConfigurationConstants.Authenticate);
                var postTask = _client.PostAsJsonAsync(_uri + subUri, userDetails).ContinueWith((taskWithResponse) =>
                {
                    var response = taskWithResponse.Result;
                    var readTask = response.Content.ReadAsAsync<UserData>();
                    readTask.Wait();
                    result = readTask.Result;
                });
                postTask.Wait();
                return result;

            }

        }

Fidler query Raw response

Community
  • 1
  • 1
Giridhar Karnik
  • 2,213
  • 4
  • 27
  • 47

4 Answers4

1

See that is allowed for all the RestClients but for javascript code to get the data cross domain you have to enable CORS.

One other way is to create a web proxy at your server and call that proxy to get the data from that url and that will return it to you.

May be a syntax error here:

  $.ajax(uri{

Change it to:

  $.ajax({
       url: uri

Still I would suggest you to call your local method which you added above.

Jai
  • 74,255
  • 12
  • 74
  • 103
  • So fiddler is a RestClient you say? – Giridhar Karnik Dec 17 '15 at 10:22
  • @HorribleGuy not rest client but it does work like a rest client as it notices the requests are made, if you want to test it with `postman` that would also get. – Jai Dec 17 '15 at 10:24
  • How? with form submission of with ajax? _last comment_ – Jai Dec 17 '15 at 10:28
  • and i would like to know what is the response `json/jsonp`? – Jai Dec 17 '15 at 10:29
  • @HorribleGuy yeah your edits are same as you can say a webproxy you can call it to serve you the response. – Jai Dec 17 '15 at 10:35
  • thanks guys..... if someone can post an answer showing how to overcome this using iframe, proxy service or any other way which does not involve server side manipulation, I can accept their answer.... – Giridhar Karnik Dec 21 '15 at 03:15
  • I got your idea now, but can I use a web-api as a proxy server? If I can, how can I fetch data from aother server using my own web-api ? – Giridhar Karnik Dec 21 '15 at 04:39
1

Thanks to Jai, I got the idea of what I had to do.... It was simple in the end..

Here is the exact code of the solution...

Step 1: The angular service which is using the in built $http service to do a AJAX call to my web-api.

Here My web-api is ProxyController

            $http.post('/Proxy', user).then(function (response) {
                successCallBack(response.data); //this is callback function 
                //this function handles the data returned by the API
            }, function (response) {
                console.log(response);
            });

Step 2: ProxyController implementation. This is the web-api which acts as the proxy server.

public class ProxyController : ApiController
{
    private string AuthenticationUri = "http://authencationserver/api/AuthenticateUser/Authenticate";
    public async Task<AuthenticationResultObject> Post(UserObject user)
    {
        // this controller just acts as an interface between the client and the actual server.
        //We are going to get the information from the actual server by making an ajax call from here
        //the server address for authenticating is http://authencationserver/api/AuthenticateUser/Authenticate
        //we need to hit this address with an user object

        HttpClient client = new HttpClient();
        HttpResponseMessage response = await client.PostAsJsonAsync(AuthenticationUri, user);

        if (response.IsSuccessStatusCode)
        {
            var result = response.Content.ReadAsStringAsync();
            var returnedObject = JsonConvert.DeserializeObject<AuthenticationResultObject>(result.Result);
            //we need the above statement to deserialize the returned json to a javascript object.
           //AuthenticationResultObject models the data that will be returned by the remote API
            return returnedObject;
        }
        return null;
    }
}
Giridhar Karnik
  • 2,213
  • 4
  • 27
  • 47
0

This is for testing purpose :

  1. Close your chromium browser
  2. Hit command in terminal

    chromium-browser --disable-web-security http://localhost/

this command disable web security and you have access cross domain sites.

Vishal Kamal
  • 1,104
  • 2
  • 10
  • 35
0

The scenario is blocked by Javascript. You can load the content in a iframe even if the Access Control Allow Origin is not present in the header. What fiddler may be doing is the same. Loading the content in the iframe and then returning the response to you with the content.