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

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?

Related

login flow with AngularJS and JWT

In my webapp, when the main page is requested by a non logged in user, I display a login page (containing only a login form). Then the user inputs its userid and pwd and an AngularJS controller issues a HTTP POST request to /connection which returns a JWT autentification token in case of accepted credentials.
Then I'd like the AngularJS controller to issue a GET on / passing the token in the header so the next loaded page is the main webapp page which the connected user can start to play with.
How do I acheive that with AngularJS. Should I use $document.location.href ? If yes how can the token set into the HTTP header ?
Thanks
You can Do it in 2 ways:
1-Use Custom Header for all the initiated Requests (doesn't matter get, post, etc..) and in here our friends posted a lot of different Approaches.
AngularJS $http custom header for all requests
2-Overriding the Header for the Request like this:
$http.get(/*The Call URL*/'http://myawesomeurl/jsondata',/*Configuration Object*/
{/*Overriding the header of the request*/
headers: {
'Content-Type': 'application/json',//request content type
'Authorization': 'token d2VudHdvcnRobWFuOkNoYW5nZV9tZQ=='//Token parameter
//,'myAwesomeHeaderParam':'the header is all yours, add or remove anything'
}
})
.success(function (data, status, headers, config) {
console.log(data);//Received data
})
.error(function (data, status, headers, config) {
console.log('Error Status:'+status);
console.log(data);//Any Server Response values in the case of error
});
//Another Way for initiating the request just for your info
/* var reqInfo = {
method: 'GET',//POST, PUT
url: 'http://myawesomeurl/jsondata',
headers: {
'Content-Type': 'application/json',//request content type (can be not used)
'Authorization': 'token d2VudHdvcnRobWFuOkNoYW5nZV9tZQ=='//Token parameter
}
//,data:{'myAwesomeParameter':'in case of post or put, etc..'} //Request body
};
$http(reqInfo).success(....*/
And you can know more about the Configuration Object here

Add Authorization Header After AJAX Call

I'm working on a web application with Angular.JS and Node.JS as the back-end.
On my login page, I'm using an AJAX call to perform the login. Upon a success login, I would like to redirect the browser to a new page but I need to add the am authorization header based on the login response.
For future AJAX calls I use Angular interceptor to add the token to each request but my problem is how to add it to the redirect call.
$http
.post('/api/authentication/login', dataToPost)
.success(function(data, status, headers, config){
$window.sessionStorage.token = data.token;
window.location.replace("/");
})
Thanks
You can add the headers like this way.
$http.defaults.headers.common.Authorization = $window.sessionStorage.token

Not able to POST data to RESTFul service from AngularJS

Hope some one can help me here.
I am trying to POST a JOSN data to restful service. But am getting below error.
Error:
XMLHttpRequest cannot load http://localhost:8080/PortalService/rest/PutService/PutLogicalTeam. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access.
This is how i am invoking the service
$http.post('http://localhost:8080/PortalService/rest/PutService/PutLogicalTeam', $scope.strLogiTeam
).success(function(data, status, headers, config) {
console.log("success");
}).error(function(data, status, headers, config) {
// Handle error
console.log(status);
});
My service.
I am not even trying to pull the data. I am just trying to check whether my service is getting invoked or not.
#POST
#Consumes("application/json")
#Path("/PutLogicalTeam")
public void putNewLogicalTeam(LogicalTeam newLogicalTeam)
{
System.out.println("Invoked");
}
I also tried like below
$http({
method: 'POST',
dataType: 'jsonp',
data: $scope.strLogiTeam,
url:'http://localhost:8080/PortalService/rest/PutService/PutLogicalTeam',
headers: {'Content-Type':'application/json'}
});
Can some one review and help. Also suggest the better way to use the web service

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?)

HTTP Basic Authorization header in request using 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.

Resources