Angular JS - $http not sending headers - angularjs

As the title suggest, I need to pass an authorization token but when I check the network console, I'm getting a 403 because the accept and authorization isn't there. NOTE: I removed my authorization token for this example
$http({
url: 'http://api.stubhub.com/search/catalog/events/v2?title="san"',
dataType: 'json',
method: 'GET',
data: '',
headers: {
"Content-Type": 'application/json',
"Authorization": 'Bearer {token}'
}
}).success(function(response){
$scope.searchResponse = response;
}).error(function(error){
$scope.error = error;
});
This seems like correct syntax? What's wrong here?
EDIT: added the XHR screenshot
EDIT: 2. Here's my network traffic, HAR via paste bin:
http://pastebin.com/fiFngZSy

setting custom headers on XHR requests triggers a preflight request.
I bet you're seeing an OPTIONS request without the Authorization header, and a corresponding response whose Access-Control-Allow-Headers header value is not listing Authorization, or the API doesn't even allow unauthorized OPTIONS requests.
I don't know the stubhub api, but does it return CORS-compliant responses?

Related

Is Excel clearing our http request authorization header attribute?

We are trying to get our Office Excel add-in to contact one of our own Web API services so it can send and receive data from it. For the request to be authorised we must fill out the Authorization header attribute. This is how we are doing the request, which works perfectly well in all of our normal web applications.
this.LoginAuth = function (authString) {
$http.defaults.headers.common.Authorization = 'Basic ' + authString;
return $http({
url: MainFactory.GetWebAPILocation() + '/API/User/AddInLoginAuth',
dataType: 'json',
method: 'POST',
data: {},
headers: {
"Content-Type": "application/json"
}
});
}
However, when the request is made through the add-in the Authorization attribute has been cleared down causing our request to fail. Is this clearing of the attribute being done by Excel? And if so, is there a way in which we can stop it?
Turns out this was a CORS issue in our Web API service.

Failed to load https://login.microsoftonline.com/common/oauth2/v2.0/token

I'm trying to get a token using the Outlook REST API after I got the code from this url https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize
I used a POST request with axios but the issue is I got this error:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
My Axios post is this:
return Axios({
method: 'post',
url: 'https://login.microsoftonline.com/common/oauth2/v2.0/token',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Access-Control-Allow-Origin':'*', Content-Type, origin, authorization, accept, client-security-token"
},
data: {
'client_id': 'xxxxxx',
'scope': 'calendars.readwrite',
'code': encodeURIComponent('000000000'),
'redirect_uri': encodeURIComponent('http://localhost:3000/storeprofile/xxxxxxxxx/outlook-scheduler'),
'grant_type': 'authorization_code',
'client_secret': encodeURIComponent('xxxxxxxxxx')
};,
responseType: 'json'
}).then((response) => {
console.log('token response: ', response);
});
I get a 200 status but can't see the token I am supposed to get in the response. The response should be a json but still nothing.
Can someone please guide me? Thank you in advance!
When you register your app, you must setup the Redirect URI/URL, usually this url will be added to the CORS header.
doc : https://developer.microsoft.com/en-us/graph/docs/concepts/auth_overview#how-do-i-get-my-app-talking-to-azure-ad-and-microsoft-graph

Ionic: Request header field token is not allowed by Access-Control-Allow-Headers in preflight response

Call from Ionic app using $http GET to Wordpress REST API is failing with error:
XMLHttpRequest cannot load http://mywordpressdomain.com/wp-json/wp/v2/categories. Request header field token is not allowed by Access-Control-Allow-Headers in preflight response.
I noticed that request header has:
Access-Control-Request-Headers:token
I tried removing the header in my $http get request.
$http({
method: 'GET',
url: url,
headers: { 'Access-Control-Request-Headers': undefined },
})
But the Access-Control-Request-Headers: token is still present in the request header. Seems like headers has no effect.
How can I fix this?
for not having any CORS issue related with http request on your localhost while developing set skipAuthorization: true... just do like this:
'$http({
method: 'GET',
url: 'http://yoururl.com/yourrequest',
skipAuthorization: true
})'

$http header 'Content-Type' not appending in the header - AngularJS

I'm using $http to do a GET request and I wanted to append 'Content-Type': 'application/json' in the header. If I don't append this header 415 (Unsupported Media Type) error is thrown.
I'm using Apache 2.2.13 with ProxyPass, in which I DO NOT say
RequestHeader append Content-Type "application/json". However if I put the RequestHeader configuration in apache $http.get works fine and the 'Content-Type' is also appended.
Scenario 1 :
Using $http, trying GET request
Request :
$http({
method: 'GET',
headers: { 'Content-type': 'application/json'},
url: '/items/?customerId=5656'
});
Chrome Network Tab :
Scenario 2 :
Using Restangular, trying the same GET request
Request :
Restangular.setDefaultHeaders({'Content-Type': 'application/json'})
Restangular.setBaseUrl('/items')
Restangular.all('').getList({customerId: '103020'}, {'Content-Type': 'application/json'});
Chrome Network Tab :
The other interesting part here is, when I do some mistakes on the Request Header like,
Restangular.setDefaultHeaders({'Contentttt-Type': 'application/json'})
and try Scenario 1, I notice the following in the Chrome Network Tab.
Scenario 3 :
Using jQuery ajax, trying the same GET request
Request :
$.ajax({
url: "/items/?customerId=103020",
type: "GET",
beforeSend: function(xhr){xhr.setRequestHeader('Content-Type', 'application/json');},
success: function() { alert('Success!'); }
});
Chrome Network Tab :
Questions :
Is it necessary to add RequestHeader append Content-Type "application/json" in Apache configuration? But if I add that I get 415 errors on POST requests.
What is the problem with AngularJS and Restangular that it won't append Content-Type headers to its network calls on GET?
What is the best solution to solve this? I have tried out all the combinations but no luck!
Versions :
Angular : 1.2.22
Restangular : 1.4.0
On the one hand, with the $http service, you can override or add your headers using $httpProvider when calling the config method on your module :
module.config(function($http) {
$httpProvider.defaults.headers.get = { 'Content-Type : 'application/json' };
});
On the other hand, with the GET method, if your API is really RESTFull, only the Accept header should be set since you are not sending JSONdata.
Thus, use the above code for your PUT/POST methods and force the Accept header for the GETmethod:
module.config(function($http) {
$httpProvider.defaults.headers.post = { 'Content-Type : 'application/json'};
$httpProvider.defaults.headers.put = { 'Content-Type : 'application/json'};
$httpProvider.defaults.headers.get = { 'Accept : 'application/json'};
});
EDIT 1:
If you want to force the content-type in a GET request, you have to add a blank data :
$http({
method: 'GET',
data:'',
dataType:'json',
headers: { 'Content-type': 'application/json'},
url: '/items/?customerId=5656'
});
Setting a Content-Type header field on an HTTP request that doesn't have a request body (such as GET) is non-sense.
Maybe what you really want is set "Accept"?

Login to Parse.com DB using API returns XMLHttpRequest header error

Here is the call I make the Parse.com's API to login the user:
var deferred = $q.defer();
$http({
method: "GET",
url: "https://api.parse.com/1/login",
headers: {
"X-Parse-Application-Id": PARSE_CREDENTIALS.APP_ID,
"X-Parse-REST-API-Key": PARSE_CREDENTIALS.REST_API_KEY,
"Content-Type": "application/json"
},
data: {
"username": credentials.username.toLowerCase(),
"password": credentials.password
}
}).success(function(data) {
deferred.resolve(data);
}).error(function() {
deferred.reject("error")
});
return deferred.promise;
When I trigger this Angular service method, I get the following error in my console:
XMLHttpRequest cannot load https://api.parse.com/1/login. Request header field Access-Control-Allow-Headers is not allowed by Access-Control-Allow-Headers.
I'm not sure how to resolve this. Here are the current contents of the common headers object for my Angular app:
Object {Accept: "application/json, text/plain, */*", Access-Control-Allow-Headers: "origin, content-type, accept"}
I implement the $http service almost exactly the same for my custom classes without error. The only difference is the URL. Can anyone provide an answer as to why I am getting this error?
EDIT: From this other question, I've gathered that the header field error is the result of the header in the Parse.com response, not in my request. But I am not sure how to proceed now.
EDIT 2: Attached is an image of the HTTP request and response headers that I get when I ping the login API URL.
Are you setting these headers for all http requests somewhere in your angular app?
I'm not sure how to resolve this. Here are the current contents of the
common headers object for my Angular app:
Object {Accept: "application/json, text/plain, */*", Access-Control-Allow-Headers: "origin,
These should come from the server only (response headers), so if they are being set somewhere in the request, then the server would error due to extra headers it was not expecting.
So here is the relevant part of the documentation from AngularJS about using the $http dependency.
params – {Object.<string|Object>} – Map of strings or objects which will be turned to ?key1=value1&key2=value2 after the url. If the value is not a string, it will be JSONified.
data – {string|Object} – Data to be sent as the request message data.
So I conflated params with data. Parse.com expects an URL-parameterized string of the username and password. My confusion was partly because I thought there was a mismatch of request and response headers. But this was not the case.
var deferred = $q.defer();
$http({
url: "https://api.parse.com/1/login",
headers: {
"X-Parse-Application-Id": PARSE_CREDENTIALS.APP_ID,
"X-Parse-REST-API-Key": PARSE_CREDENTIALS.REST_API_KEY,
"Content-Type": "application/json; charset=utf-8"
},
params: {
"username": credentials.username.toLowerCase(),
"password": credentials.password
}
}).success(function(data, status, headers, config) {
deferred.resolve(data);
}).error(function(data, status, headers, config) {
deferred.reject("error")
});
Additional note: For any Angular developers out there who are concerned about the security of user credentials, you will need to set up SSL for your site to ensure that this data does not fall victim to a man-in-the-middle attack. For information on how to set up SSL with Parse.com, read this article.
If, you do not want to pay for an SSL certificate as DigiCert prescribes (e.g. this app is not for customers, but for internal purposes), check out this article for information on how to create your own SSL certificate and save yourself +$100/year.

Resources