I need to make a call to an API for my Angular app. Before I can make the call I have to retrieve an AUTH token. This can be accomplished by sending my username and password and then the AUTH token is in the header of the reply. My Angular code seems pretty straightforward, but for some reason two calls are going out to the API. Below is a really basic version of the code as well as the XHR responses in Chrome's debugging tools
'use strict';
var app = angular.module('alpha', ['ngRoute']);
app.controller('apictrl', function($scope, $http, $route, MyAPIAuth) {
MyAPIAuth.then(function(response, status, headers) {
console.log(response);
console.log(status);
console.log(headers);
$scope.authcode = response;
})
});
app.service('MyAPIAuth', function($http) {
var APIauthURL = "https://phoenix.discoverydb.com/papi/login";
var credentials = {
"username": <insert username>,
"password": <insert password>
};
return $http.post(APIauthURL, credentials);
});
As you can see from the image below I receive two response—both 200! Yet, nothing registers in the console. The first response does have the AUTH token that I'm looking for in it. I just can't get to it.
Related
I'm building a SPA with AngularJS with communication to a service (JAVA).
When user sends his username/pass, service sends back both: Acces token and Refresh token. I'm trying to handle: if I get response with status 401, send back refresh token and then send your last request again. I tried to do that with including $http, but angular doesn't let me include it in this interceptor. Is there any way to recreate the original request with this response parameter I'm recieving?
Something like:
I get 401
save my request
if I have a refresh token send that refresh token
on success resend my request
on error redirect to /login page
'use strict';
angular.module('testApp')
.factory('authentificationFactory', function($rootScope, $q, $window, $location, CONF) {
return {
request: function(config) {
config.headers = config.headers || {};
if ($window.sessionStorage.token) {
config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
}
console.log(config);
$rootScope.lastRequest = config;
return config;
},
response: function(response) {
console.log($rootScope.lastRequest);
if (response.status === 401) {
if ($window.sessionStorage.refreshToken) {
//Save, request new token, send old response
//if it fails, go to login
$location.url('/login');
} else {
$location.url('/login');
}
}
return response || $q.when(response);
}
};
});
Bonus Question (the main question is more important): There are 2 mobile apps that will also connect to my service, and when I log in from my web app, and few moments later from my mobile app, mobile app takes a new refresh token and my web app's refresh token is valid no more. What would be the best option for dealing with that?
Thank you for your time,
Best regards
Have a look at this: https://github.com/witoldsz/angular-http-auth.
He uses a buffer to replay the requests after authentication.
I would strongly advise against sending and storing refresh tokens on SPAs like Angular.
If you are using session storage or local storage, you are opening a window of opportunity for the this refreshToken to be captured, either by a XSS attack, or by the user leaving the computer unattended.
See this article or this question for more info.
I'm trying to create a simple app using Angular that will consume my API. I'm using a VM to run the code, and I access it on my computer, so to call the API from my machine I can use cURL or any other HTTP client and everything works. An example:
curl -k --user damien#email.com:password https://api.my.domain.com/v1/traveler/get
And that would return a list of travelers for example. I need to "trust" the certificate as it is not valid. So on the browser at first the call would return net::ERR_INSECURE_RESPONSE, so I'm just going to the API URL and add the exception and now I don't have this issue anymore. Then I had to add basic authentication, and it seems to work. Let's see what is my code and please let me know if you see anything wrong, I'm following this tutorial that consume an external API: http://www.toptal.com/angular-js/a-step-by-step-guide-to-your-first-angularjs-app
app.js:
angular.module('TravelerApp', [
'TravelerApp.controllers',
'TravelerApp.services'
]);
services.js:
angular.module('TravelerApp.services', [])
.factory('TravelerAPIService', function($http) {
var travelerAPI = {};
$http.defaults.headers.common.Authorization = 'Basic ABC743HFEd...=';
travelerAPI.getTravelers = function() {
return $http({
method: 'GET',
url: 'https://api.my.domain.com/v1/traveler/get'
});
}
return travelerAPI;
});
Finally, the controllers.js:
angular.module('TravelerApp.controllers', [])
.controller('travelersController', function($scope, TravelerAPIService) {
$scope.travelersList = [];
TravelerAPIService.getTravelers()
.success(function(data) {
console.log('SUCCESS');
$scope.travelersList = data;
})
.error(function(data, status) {
console.log('ERROR');
$scope.data = data || "Request failed";
$scope.status = status;
});
});
The error status code is 0, and the error data is an empty string.
Precisions:
I have the same behavior with an HTTP POST query.
I am sure :
no request have been made on the server
it's angular that don't sent the query
And finally I find the answer:
Since I (and probably you) are sending on a self signed httpS server. Chrome flag it as none safe.
I fix this issue by putting the address on my browser and manually accept the certificate.
Probably related : XMLHttpRequest to a HTTPS URL with a self-signed certificate
I would suggest to use Trusted CA Signed SSL Certificate rather then Self-Signed Certificates which would solve your problem as most browsers do not accept the self signed certificates like Google Chrome,Firefox,etc.
I've been hunting for a few hours now and can't seem to find any information specific to my setup so here goes.
I'm using the MEAN stack and wanting to use the Twitter API in my angular app. I have all the required keys and trigger a twitter api authentication on the server side using Node, then pass the token I get in response to my angular pages. I was hoping to be able to use this token to make requests to the api from an angular service. The request I'm trying to get working the moment is to fetch a given user's profile object. I've attached my service method below. The error I get when I run it is a 405 method no allowed, no access-control-allow-origin header is present.
angular.module('tms.system').factory('Twitter', ['$log', '$q', '$http', '$window', 'twitter', 'Global', function($log, $q, $http, $window, twitter, Global) {
return {
findProfile: function(handle) {
var deferred = $q.defer();
var config = {
timeout:3000,
headers: {
'Authorization': 'Bearer ' + Global.twitterToken,
'X-Testing' : 'testing'
}
};
$http.get('https://api.twitter.com/1.1/users/show.json?screen_name=' + handle, config).
success(function(data) {
$log.info(data);
deferred.resolve(data);
}).
error(function(status) {
$log.error(status);
});
return deferred.promise;
}
};
}]);
Just for future reference, as stated in the comments of maurycy's answer {and being myself trying to get tweets just from Angular without succes}, the best approach for this would be to get them from some backend.
I believe you should use $http.jsonp with a JSON_CALLBACK to get it to work, it's not going to happen with $http.get for sure
In my angularjs application I am communicating with a backend server that requires basic access authentication via http header. I have implemented the authentication mechanism on the client side as described here.
angular.module('myAuthModule')
.config(['$httpProvider', '$stateProvider',
function ($httpProvider, $stateProvider) {
$httpProvider.interceptors.push('securityInterceptor');
}])
.factory('securityInterceptor', ['$location', '$window', '$q',
function ($location, $window, $q) {
return {
request: function (config) {
config.headers = config.headers || {};
if ($window.sessionStorage.token) {
config.headers['Auth-Key'] = $window.sessionStorage.token;
}
return config;
},
response: function (response) {
if (response.status === 401 || response.status === 403) {
$location.path('/login');
}
return response || $q.when(response);
}
};
}
]);
So far so good, handling xhr requests within the angular app works as expected.
The problem is that I need to provide a download link for pdf documents. My backend server has a /Document/Pdf/:id resource that serves a application/pdf response with ContentDisposition: attachment which also requires authentication. I understand that I cannot initiate a download using xhr, however both providing a link to the document download via ngHref and calling a function that does for example $window.open('/Document/Pdf/13') lead to a 401 Unauthorized response by the server.
What am I missing here?
Having explored the possibilities given by #Geoff Genz with the addition of a fourth - data-uri option, which unfortunately does not allow defining filenames - I decided to go for a different approach.
I added a method to the API which generates a one-time download link based on a normally authenticated request and download it straight away. The angular handler becomes very simple
.factory('fileFactory', ['$http', '$window',
function ($http, $window) {
return {
downloadFile: function (fileId) {
return $http(
{
method: "POST",
data: fileId,
url: '/api/Files/RequestDownloadLink',
cache: false
}).success(function (response) {
var url = '/api/File/' + response.downloadId;
$window.location = url;
});
}
};
}]);
This is not perfect but I feel is least hack-ish. Also this works for me because I have full control of the front- and back-end.
There is not a simple solution to this. You've already discovered that you cannot download via Ajax, so you can't set a custom header that way. Nor can you set a custom header on a browser generated GET (like an href) or POST (like a form submit). I can suggest three different approaches, all of which will require some modifications on your server:
(1) Use Basic or Digest auth on your web page, so the browser will generate and send the Authorization header with those credentials.
(2) Set the token in "authorization" cookie that will be passed with the request and validate the token server side.
(3) Finally, the way we've implemented this is to use a POST request instead of a GET for the download. We POST to a hidden IFrame on the same page and have the server set the appropriate Content-Disposition header such as "attachment; filename="blah.pdf"" on the response. We then send the authorization token as a hidden field in the form.
None of these are ideal, and I know our solution feels kind of hacky, but I've not seen any more elegant approaches.
I'm working with a restful API that when authenticating a user successfully, the request returns a token. The token is then added as a header on every request like this:
Authorization: Bearer <token>
I struggled to find a good way to do authentication without a lot of code bloat.
I came up with a good solution using HTML5 sessionStorage. Here's a simple example:
// Main module declaration
var myapp = angular.module('myapp', []);
// Set some actions to be performed when running the app
myapp.run(['$location', '$rootScope',
function($location, $rootScope) {
// Register listener to watch route changes.We use this to make
// sure a user is logged in when they try to retrieve data
$rootScope.$on("$routeChangeStart", function(event, next, current) {
// If there is no token, that means the user is not logged in
if (sessionStorage.getItem("token") === null) {
// Redirect to login page
window.location.href = "login.html";
}
});
}]);
// A controller for the login page
myapp.controller('LoginController', ['$scope', '$http',
function($scope, $http) {
// If a user has check the "remember me" box previously and the email/pass
// is in localStorage, set the email/password
// Login method when the form is submitted
$scope.login = function() {
// Authenticate the user - send a restful post request to the server
// and if the user is authenticated successfully, a token is returned
$http.post('http://example.com/login', $scope.user)
.success(function(response) {
// Set a sessionStorage item we're calling "token"
sessionStorage.setItem("token", response.token);
// Redirect to wherever you want to
window.location = 'index.html';
});
};
}]);