HTTP Basic Authorization header in request using AngularJS? - angularjs

I am trying to use AngularJS with an external API. The API uses HTTP Basic for authentication.
I have looked around at how to do this but nothing seems to work. The OPTIONS request is always sent without the Authorization header.
Here is some example code:
var app = angular.module("BE", []);
app.controller("NextCtrl", function ($scope, $http) {
$http.defaults.headers.common['Authorization'] = 'Basic encoded_credentials';
$http.get('http://api-url.com').
success(function(data, status, headers) {
$scope.event = data.Event;
$scope.race = data.Race;
$scope.entrants = data.Entrants
}).
error(function(data, status, headers, config) {
// log error
});
});
How can I make my requests with the Authorization header set for every request?

You can't control that because OPTIONS is sent by a browser. A browser removes any authorization data in OPTION requests (see CORS W3C Recommendation).
In most cases Authorization header for OPTIONS-requests isn't needed because the response includes only CORS headers and doesn't perform any action.

Related

Angular http.get + WebApi = Cors failure

on server side I have a C# web api including a controller attributed like this on class level:
[EnableCors(origins: "http://localhost:51664,http://localhost,...", headers: "*", methods: "*")]
I can make ajax calls, e.g. form localhost just fine.
Now I am starting with AngularJS and the http.get-method fails with the following message:
XMLHttpRequest cannot load http://localhost:8081/DividendsManager.Web.Api/api/securities/GetSecurities?yearsDividendsDontDecrease=40. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
This is my AngularJS code:
<script>
var myApp = angular.module('myApp', []);
myApp.controller("myController", function($scope, $http) {
var onSuccess = function(data, status, headers, config) {
$scope.data = data;
};
var onError = function(data, status, headers, config) {
$scope.error = status;
}
var promise = $http.get("http://localhost:8081/DividendsManager.Web.Api/api/securities/GetSecurities?yearsDividendsDontDecrease=40");
promise.success(onSuccess);
promise.error(onError);
});
</script>
In Fiddler, I can see, that the header of the AngularJS-HTTP-Get request has an "Origin: null" entry, which seems to be related to the problem. I think, if instead "null" the value would be "http://localhost", it should work.
Can anyone help me out?
Thank you!
Could it be because in your [EnableCors] attribute, you need to change headers: "", methods: "" to headers: "*", methods: "*"?
Also, you should not include a forward slash at the end of the origins url (if you did).
We had the same issue in our project and we tried so many options as per the suggestions from various web sites. But the thing that worked/working in our case is writing custom CORS provider as mentioned here.
Upppps!
When running in the fresh air today I suddenly was aware why Origin was null. It was, because I was not calling the web site in IIS, but instead I opened the file directly in the file system. For sure, there was no valid URL when doing so, and the Origin was null for the web server.

Angular Authorization header is null on CROSS DOMAIN API call. Why?

I have an Angular (1.3.8) SPA with a factory method that is attempting to add a basic authorization header before making a cross-domain API call.
The API is an ASPNET WEB API but has CORS totally enabled. The API is using basic auth message handler
The problem is that in the first call to the API there is no AUTHORIZATION header at all even though the code making the API call looks like this:
$http.defaults.headers.common.Authorization = 'Basic blah...';
$http.get('http://my-webapi-url').
success(function(data, status, headers, config) {
...
}).
error(function(data, status, headers, config) {
alert('error ' + status);
});
The API is not receiving an AUTHORIZATION on the initial call, and is rejecting the call with 401 of course. Why isn't there an AUTH header from the start?

angularjs basic authentication headers

I'm trying to connect to API and send authentication headers.
I'm using Base64 as described here How do I get basic auth working in angularjs?
function Cntrl($scope, $http, Base64) {
$http.defaults.headers.common['Authorization'] = 'Basic ' + Base64.encode('----myusername----' + ':' + '----mypass---');
$http({method: 'GET', url: 'https://.../Category.json'}).
success(function(data, status, headers, config) {
console.log('success');
}).
error(function(data, status, headers, config) {
alert(data);
});
}
but i'm getting this error
XMLHttpRequest cannot load https://.../Category.json?callback=?. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://....com' is therefore not allowed access. The response had HTTP status code 400.
Looks like you are running into issues with Cross-Origin Resource Sharing (CORS). Have a read of:
How does Access-Control-Allow-Origin header work?
If you control the server then you can have it send back an appropriate Access-Control-Allow-Origin header as per what the server code in the question you referenced (How do I get basic auth working in angularjs?)

Requesting data to Sharepoint 2013 using rest api service to integrate with angular app

I am learning sharepoint 2013 for a required incoming project. I has never worked on .net or any other ms technology so i would appreciate if the answers are dumb proof.
I have a server that is running sharepoint 2013 and iis v8.0
Currently i am having some issues, but the main one is that i am trying to access the api service from an angular application. I setted the mapping for intranet to the ip of the server and i can access the api through to the web browser.
I also setted the http response headers to "Access-Control-Allow-Origin" : * in iis. However when i try to access the api using the angular $http object i am getting a message that says XMLHttpRequest cannot load http://x.x.x.x/_api/web. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http:// localhost : 9000' is therefore not allowed access. The response had HTTP status code 401.
The idea is that the angular application is totally independant of sharepoint and any .net technology. All i want to do is use the rest api to get/edit data.
The request i am making looks like this:
angular.module('angYeoman2App')
.factory('SharePointJSOMFactory', function SharePointJSOMFactory($http, $q) {
var deffered = $q.defer();
var data = [];
var myService = {};
SharePointJSOMFactory.getTasksRESTAppWeb = function() {
var restQueryUrl = "http://x.x.x.x/_api/web";
$http({
headers: { 'Accept': 'application/json; odata=verbose' },
method: 'GET',
url: restQueryUrl
})
.success(function(data, status, headers, config){
console.log(data);
deffered.resolve();
})
.error(function(data, status, headers, config){
console.log('error', data)
deffered.resolve();
});
return deffered.promise;
};
SharePointJSOMFactory.data = function() {
return data;
};
return SharePointJSOMFactory;
});
Any idea what i am doing wrong? I has read that i need to add <% Response.AddHeader("Access-Control-Allow-Origin", "*") %> somewhere, but i don't have any idea to what file.
I also have another problem (not so relevant at this point): When i try to access to a subsite using the ip address it seems it is applying the theme of the parent and it doesn't load the content of the subsite. Any idea why?
Any help is welcome. Tks for your time, have a nice day.

Getting JSON data using Angular JS's $http service

I need to get JSON data from a server with URL :
http://xxxx.xxxx.xxxx.xxxx:8084/inpulse/api/user/listall
Here's my angular code:
var app = angular.module('app',[]);
app.controller('Controller', function ($scope,$http) {
$scope.email="";
$scope.password="";
$scope.sample="";
$http({
method: 'GET',
url: 'http://xxxx.xxxx.xxxx.xxxx/inpulse/api/user/listall',
})
.success(function (data, status, headers, config) {
var ret = data;
$scope.sample = JSON.stringify(ret);
})
.error(function (data, status, headers, config) {
alert(status);
// something went wrong :(
});
});
Now the same code worked when i used a JSON test URL like http://ip.jsontest.com/.
Its Definitely not a problem with the server because I tested it with a REST client and got a response. I can't figure out what I'm doing wrong.
It might be a CORS configuration issue.
If you are trying to access the server from a page that is not in the same domain/origin, you'll get an error because the server is not configured to allow CORS.
The error reported by Chrome looks like this:
XMLHttpRequest cannot load http://xxxx.xxxx.xxxx.xxxx/inpulse/api/user/listall. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://fiddle.jshell.net' is therefore not allowed access.
Other than that the code seems to work just as expected.

Resources