I've built an API for my web app, which is built using MEAN stack. Now I am trying to use this API on mobile client side which is built using Ionic Framework. I'm using this code to perform an $http call to API:
$http.post(ServerIP+'/login', {username: $scope.credentials.username, password: $scope.credentials.password}).success(function(response) {
$scope.authentication.user = response;
$location.path('/');
}).error(function(response) {
$scope.error = response.message;
});
It gets a valid response with user object, but if I try to get some info from protected parts of an API it doesn't work and auth is being reset.
On web app, I use the same code and everything works fine. This issue happens only on Ionic app. I've set the CORS like that:
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
// intercept OPTIONS method
if ('OPTIONS' === req.method) {
res.sendStatus(200);
}
else {
next();
}
});
Please, help me!
Try adding this line in your angular config:
app.config(function ($httpProvider) {
$httpProvider.defaults.withCredentials = true;
});
I've solved this problem by adding Token-Based Authentication.
Here's the article which shows how to do that: https://auth0.com/blog/2014/01/07/angularjs-authentication-with-cookies-vs-token/
Sample of my "login" route:
router.post('/login', passport.authenticate('local'), function(req, res, next){
if (req.user) {
var token = jwt.sign(req.user, secret, {expireInMinutes: 60*24*7});
res.json(token);
};
});
For getting user object on protected routes, I'm using expressJwt({secret: secret})
middleware.