1

I'm doing a cross origin request to fetch a json response from the url which has a Basic authentication. So on tap of the button, am setting the headers for basic authentication. When I print out the values before the request has been sent I see them. But when i check the chrome dev tool for request I don't see the headers been set. Also the request turns to be an "Options" request from "GET" request and the response comes as 401 unauthorized. Is there anything am missing?

 <paper-input type="search" value="{{imageUrl}}" placeholder="Enter Image URL"></paper-input> 
  <div class="buttons">
    <paper-button on-tap="getData" autofocus>Search</paper-button>
  </div>
  <iron-ajax
  id="xhr"
  url="https://api.com/v1"
  params='{"url":"some query value"}'
  handle-as="json"
  method="GET"
  last-response="{{ajaxResponse}}"></iron-ajax>

  getData: function(){
    this.$.xhr.headers['X-Requested-With'] = "XMLHttpRequest";
    this.$.xhr.headers['Authorization'] = this.makeHeaders(this.user, this.password);
    this.$.xhr.generateRequest();
  }
Muthu Rg
  • 632
  • 1
  • 6
  • 18
  • This lends me to believe that the browser is sending a preflight request with the options method to "https://api.com/vi" and you need to handle that option method by sending back http status 200 and then you call should be handled normally. – getbuckts Jul 26 '16 at 16:35
  • Check these urls: http://stackoverflow.com/questions/30632200/standalone-spring-oauth2-jwt-authorization-server-cors/30638914#30638914 http://stackoverflow.com/questions/8685678/cors-how-do-preflight-an-httprequest – getbuckts Jul 26 '16 at 16:37
  • @getbuckts Its actually an third party api service i'm hitting and it works when i'm doing it from postman. Also I tried with safari and firefox with same failure message. Not sure what i'm doing wrong – Muthu Rg Jul 26 '16 at 17:43
  • can you show what "this.makeHeaders()" code does? – getbuckts Jul 26 '16 at 19:01
  • makeHeaders: function(user, password){ return "Basic " + btoa(user + ":" + password); }, – Muthu Rg Jul 26 '16 at 19:05

1 Answers1

1

By default iron-ajax does not send the credentials by default for cross-site requests

You can change this by setting the withCredentials property on the iron-ajax:

<iron-ajax
  id="xhr"
  url="https://api.com/v1"
  params='{"url":"some query value"}'
  handle-as="json"
  with-credentials="true"
  method="GET"
  last-response="{{ajaxResponse}}"></iron-ajax>

or

this.$.xhr.withCredentials = true;
Ümit
  • 17,379
  • 7
  • 55
  • 74