Angular authentication using Passport for Ionic App - angularjs

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.

Related

How to connect from angular to express server running on the same machine?

I am very new to express (and backend), and I am learning. So I mounted an express server on my machine by running express and npm install, and then overwriting the app.js with a simple code that serves something on /test
var express = require('express')
var app = express()
app.all('/*', function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Content-Type,X-Requested-With');
next();
});
app.get('/test', function (req, res) {
res.send('hi???');
});
app.listen(3100);
On my frontend, I am working with angular, it is running on localhost:3000, but when I run
function TestController ($http) {
var vm = this;
$http.get('http://localhost:3100/test')
.then(function (response) {
console.log(response);
});
}
It throws the following error:
XMLHttpRequest cannot load http://localhost:3100/test. Request header field Pragma is not allowed by Access-Control-Allow-Headers in preflight response.
I thought it could be a problem on the backend, but when I run
function TestController ($http) {
var vm = this;
var httpRequest = new XMLHttpRequest();
httpRequest.open('GET', 'http://localhost:3100/test', true);
httpRequest.send(null);
}
It won't throw any error, so I guess it is a problem with my angular configuration, but I cannot figure out where or what the problem is... how can I fix this? any help tweaking the backend or the frontend to fix this will be really helpful!
I already tried this, but it won't work, AngularJS POST Fails: Response for preflight has invalid HTTP status code 404 it doesn't makes any difference :(
Given the description of the problem, it was not about CORS, it had to do with headers not being handled correctly by the backend. Running the app on firefox, firebug suggests to add the token pragma to Access-Control-Allow-Headers... and then, another unkown header would jump up, now called cache-control so I only had to modify the app.js.
For anyone having this same problem, you just need to add the problematic headers to the string on 'Access-Control-Allow-Headers' :)
app.all('/*', function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers',
'Content-Type,X-Requested-With,cache-control,pragma'
+ otherHeadersSeparatedByComma);
next();
});

Session undefined in Express when AngularJS as frontend

I have written webservice using NodeJS and Express. Service is running on port 8090. Also I wrote frontend in AngularJS and running on port 8080.
Mongo has username and password stored of all users
When I login via HTML5/AngularJS frontend, the AngularJS app in turn calls the http post request of express. User is authenticated. And I set req.session.email = the email address of the user.
I even am able to return and check in console log of AngularJS that req.session.email was set correct in express
The problem is that I created an authentication function called "restrict" in Express to act as middleware function to give access to other get/post requests only if req.session.email is not undefined.
But even after session has been set, when this other get/post request of Express are calling by AngularJS app, this "restrict" function blocks the calls because it receives req.session.email as undefined
Both AngularJS and Express are on the same machine. But I don't think this is the problem.
Express Code Snippet
var url = 'mongodb://127.0.0.1:5555/contacts?maxPoolSize=2';
var mongojs = require('mongojs');
var db = mongojs(url,['data']);
var dbauth = mongojs(url,['users']);
// var request = require('request');
var http = require('http');
var express = require('express');
var cookieparser = require('cookie-parser');
var app = express();
var bodyParser = require('body-parser');
var session = require('express-session');
app.use(cookieparser());
app.use(session({secret:'v3ryc0mpl!c#t3dk3y', resave: false, saveUninitialized: true}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
var user_session;
app.all('*',function(req, res, next){
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});
function restrict(req,res,next){
try{
if(req.session.email){
next();
}
else{
res.send('failed');
res.end();
}
}
catch(err){
res.send('failed');
res.end();
}
};
app.post('/login',function(req,res){
//removed DB function from here to make the code look simple
req.session.email = req.body.email;
req.session.password = req.body.password;
});
app.get('/loggedin',restrict,function(req,res){
res.send(true);
});
AngularJS Function that calls the Express function to check session status
var resolveFactory = function ($q, $http, $location,LoginDetails) {
var deferred = $q.defer();
$http.get("http://127.0.0.1:8090/loggedin")
.success(function (response) {
if(response == true){
deferred.resolve(true);
}
else
{
deferred.reject();
LoginDetails.setemail('');
LoginDetails.setpassword('');
$location.path("/");
}
})
.error(function (err) {
deferred.reject();
$location.path("/");
});
return deferred.promise;
};
Fundamentally the AngularJS Resolve Function that I created should be successful but it is not. It is failing. Am using live-server to run HTML/AngularJS on my laptop and nodemon to run Express app
Ok! So the reason is that AngularJS is running on a different port 8080
Express was running on port 8090. This means that if AngularJS calls an API of Express, the session of Express would be lost unless Express allows session to be passed on to AngularJS and AngularJS calls the API of Express with {withCredentials: true} parameter set. Below are the changes that I had to make to get the session maintained when AngularJS and ExpressJS were running on different ports
In AngularJS makes sure any API you call of Express, it should have
{withCredentials: true} like this
$http.get('http://expressdomainname:expressport/api',{withCredentials: true})
like wise in case you use $http.post
the parameter {withCredentials: true} is important
Now on the Express side
make sure you have app setting like this
app.all('*',function(req, res, next){
//Origin is the HTML/AngularJS domain from where the ExpressJS API would be called
res.header('Access-Control-Allow-Origin', 'http://localhost:8080');
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type');
//make sure you set this parameter and make it true so that AngularJS and Express are able to exchange session values between each other
res.header("Access-Control-Allow-Credentials", "true");
next();
});
Please feel free to ask me question in case you have about this topic. I spent days to resolve this.

OAuth Token Response to Angular View (cookie)

I've been struggling with this for a couple hours now and need some help. I've created a simple app that presents the user with a "Login Using Google" button in an angular view that redirects the user to the Google Oauth page. Here's the controller code that calls the login() function when the button is pressed:
angular.module('dashApp').controller('SigninCtrl', function ($scope) {
$scope.login=function() {
var client_id="191641883719-5eu80vgnbci49dg3fk47grs85e0iaf9d.apps.googleusercontent.com";
var scope="email";
var redirect_uri="http://local.host:9000/api/auth/google";
var response_type="code";
var url="https://accounts.google.com/o/oauth2/auth?scope="+scope+"&client_id="+client_id+"&redirect_uri="+redirect_uri+
"&response_type="+response_type;
window.location.replace(url);
};
});
The redirect URI set in my google project redirects to a server page to this server page:
'use strict';
var _ = require('lodash');
var request = require('request');
var qs = require('querystring');
var fs = require('fs');
// Get list of auths
exports.google_get = function (req,res){
var code = req.query.code,
error = req.query.error;
if(code){
//make https post request to google for auth token
var token_request = qs.stringify({
grant_type: "authorization_code",
code: code,
client_id: "191641883719-5eu80vgnbci49dg3fk47grs85e0iaf9d.apps.googleusercontent.com",
client_secret: process.env.GOOGLE_SECRET,
redirect_uri: "http://local.host:9000/api/auth/google"
});
var request_length = token_request.length;
var headers = {
'Content-length': request_length,
'Content-type':'application/x-www-form-urlencoded'
};
var options = {
url:'https://www.googleapis.com/oauth2/v3/token',
method: 'POST',
headers: headers,
body:token_request
};
request.post(options,function(error, response, body){
if(error){
console.error(error);
}else{
//WHAT GOES HERE?
}
});
}
if(error){
res.status(403);
}
}
I'm able to exchange the code returned by google for an auth token object successfully and log it to the terminal. I've been told that I should set a cookie using:
res.setHeader('Content-Type', 'text/plain');
res.setCookie('SID','yes',{
domain:'local.host',
expires:0,
path:'/dashboard',
httpOnly:false
});
res.status(200);
res.end();
Followed by a controller on the page I'm directing the user to that validates the session.
What am I doing wrong?
Since you have already done the hard work so there is no point talking about passport.js which is actually written to simplify these kind of social login authentication.
So let's come directly to session implementaion logic.
You need to set the following header in your app.js/server.js :
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization');
next();
});
Let's say you are returning this token after successful login :
{
name : "some name",
role : "some role",
info : "some info"
}
You can have a client side function in your angular service or controller :
function(user,callback){
var loginResource = new LoginResource(); //Angular Resource
loginResource.email = user.email;
loginResource.password = user.password;
loginResource.$save(function(result){
if(typeof result !== 'undefined'){
if(result.type){
$localStorage.token = result.token;
$cookieStore.put('user',result.data);
$rootScope.currentUser = result.data;
}
}
callback(result);
});
}
LoginResource calls your REST endpoint which returns auth token.
You can store your auth token in localStorage and cookieStore.
localStorage makes sure that we are having the token saved even when user has closed the browser session.
If he clears the localStorage and cookieStorage both then log him out as you don't have any valid token to authorize user.
This is the same logic which i am using here. If you need more help then let me know.

passport.js auth0 strategy Cross rigin request error

I am trying to use auth0 for social validation in my web app
i configured the app like this
auth0 : {
domain : "mydomain",
clientID : "myid",
clientSecret: "mysecret",
callbackURL: "/callback"
},
I request login from angular controller using http get to node backend like
app.get('/auth/:connection', function(req, res, next) {
passport.authenticate('auth0', {connection: req.params.connection}, function(err, user, info) {
}) (req, res, next);
});
I will call like auth/facebook for facebook login from angular client side controller.
The callback route is configured like this
app.get('/callback', passport.authenticate('auth0', { failureRedirect: '#!/authServiceImpl/login' }),
function(req, res) {
console.log('auth0 callback');
console.log(req.user);
}
);
Every time I am getting Cross origin request error.
What I am doing wrong ?
I request login from angular controller using http get to node backend like
You cannot perform OAuth over XHR. Instead of doing $http.get('/auth/whatever') you'd need to do window.location.pathname = '/auth/whatever' or window.open('/auth/whatever')

Authentication when using angularjs and passportjs

I am currently using passportjs for authenticaton.
I have come across a stage where i need to ensure the user is authenticated if the url is typed in the browser/ I have been using the passportja example which has the following:
app.get('/admin', ensureAuthenticated, function(req, res){
console.log('get admin');
res.render('admin', { user: req.user });
});
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) { return next(); }
res.redirect('/login')
}
I am using angularjs for routing so my get does not work and run the ensure authenticated.
How should this be implemented?
With AngularJS, you need to restrict the display of templates to the user.
So, let us say you have the following code in AngularJS:
$routeProvider.when('/admin', {
templateUrl: '/partials/admin-page.html'
});
When the user tries the /admin route, AngularJS will then request the template /partials/admin-page.html.
Thus, in your nodeJs server, you then implement the following code:
app.get('/partials/admin-page.html', ensureAuthenticated, function (req, res) {
res.render('admin', { user: req.user});
});

Resources