How to protect static folder in express with jwt - angularjs

I have application which is build on nodejs and angularjs ,where i am using jwt token based authentication to authenticate and the api calls that is working fine
Even when the user is not login now application is service all the static resources how to avoid loading the application if the user is not login and redirect the user to login page
Finally i was able to fiqure it out in the app.js floder add the code sinpet
app.use('/app/view/*', function(req, res, next) {
if (!req.headers['authorization'] ) {
res.sendfile('app/views/Error.html');
} else {
next();
}
});
this mean for the request coming with /app/view/ check if the header of the request contains the token generated with jwt

If your JWT is stored in a cookie you can use a road like this one :
router.all('/*', function(req, res, next){
if (!req.cookies.session) {
return res.json("ERROR");
}
else {
ValidateCookieFunction(req.cookies.session, function(auth_state) {
if (!auth_state)
return res.json("ERROR");
else
next();
});
}
});
else you can provide your JWT in an HTTP-Header
router.all('/*', function(req, res, next){
if (!req.headers['x-access-token']) {
return res.json("ERROR");
}
else {
ValidateJWTFunction(req.headers['x-access-token'], function(auth_state) {
if (!auth_state)
return res.json("ERROR");
else
next();
});
}
});

Related

how to restrict admin signing in through usersignin page passport authentication and mongodb

we are developing one e-commerce project in that i am signing in admin page it automatically admin and user signing page. how we restrict to stop admin to user signing page. in this i am using passport authentication.
function ensureOnlyAdmin(req, res, next){
if(req.isAuthenticated()){
if (req.user.role === 'admin')
{
return next();
}
else {
req.logout();
res.redirect('/admin');
}
}
else {
res.redirect('/admin');
}
}
above code for authentication
router.post('/admin', passport.authenticate('authAdminWeb', {successRedirect:'/admin/dashboard', failureRedirect:'/admin',failureFlash: true}),function(req, res) {res.redirect('/admin/dashboard');});
above code for posting

Node / Angular Authentication

I'm trying to figure out how to authenticate a user using node.js and angular.js. I have a node server which has a route pointing to api/login. Users can register and log in everything works. But when I get to the client side, I have no idea where to go. I have set up a http interceptor which send the user back to the login page if a session doesn't exist. I am currently using session express. Below are snippets of my code:
Login Route:
router.post('/login', function(req, res, next) {
var username = req.body.username;
var password = req.body.password;
User.findOne({username: username, password: password}, function(err, user) {
if(err) {
console.log(err);
res.status(500).send();
}
if(!user) {
res.status(404).send();
} else {
console.log('Set' + user);
req.session.user = user;
res.status(200).send();
}
});
Protecting this endpoint:
app.get('/api/endpoint', function(req, res) {
if(!req.session.user) {
console.log('Unauthorized');
res.status(401).send();
} else {
console.log('Logged in');
res.status(200).send();
}
});
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use('/api', require('./routes/login'));
app.use('/api', require('./routes/register'));
app.listen(port);
I'm not sure if this is detailed enough but I know there's something really simple going wrong here I just cannot see it haha! Any help would be greatly appreciated!

Create account with social login (facebook) and authenticate it angular-fullstack generator

I'm facing a problema with social signup because its not logging after its created as in local signup. When redirects, api/users/me is not accessible..is unauthorized (401), different from what i get in local signup, that redirects with user information.
in facebook/index.js I have default gets
.get('/', passport.authenticate('facebook', {
scope: ['email', 'user_about_me'],
failureRedirect: '/signup',
session: false
}))
.get('/callback', passport.authenticate('facebook', {
failureRedirect: '/signup',
session: false
}), auth.setTokenCookie);
and in auth.service.js I have the default functions
function isAuthenticated() {
return compose()
// Validate jwt
.use(function(req, res, next) {
// allow access_token to be passed through query parameter as well
if (req.query && req.query.hasOwnProperty('access_token')) {
req.headers.authorization = 'Bearer ' + req.query.access_token;
}
validateJwt(req, res, next);
})
// Attach user to request
.use(function(req, res, next) {
User.findByIdAsync(req.user._id)
.then(function(user) {
//user here is undefined, it shouldn't be. i want to find out why.
if (!user) {
return res.status(401).end();
}
req.user = user;
next();
})
.catch(function(err) {
return next(err);
});
});
}
function signToken(id, role) {
return jwt.sign({ _id: id, role: role }, config.secrets.session, {
expiresInMinutes: 60 * 5
});
}
/**
* Set token cookie directly for oAuth strategies
*/
function setTokenCookie(req, res) {
if (!req.user) {
return res.status(404).send('Something went wrong, please try again.');
}
var token = signToken(req.user._id, req.user.role);
res.cookie('token', token);
res.redirect('/');
}
Could anyone help me with this...Am I missing something?
Thanks in advance.
I had the similar issue. I had modified Angular full-stack code with a customizable backend URL.
https://github.com/kannach/AFSPhonegap/blob/master/client/components/services/config.service.js
I was testing the facebook login in localhost, whereas my backend url was pointing to my production server. Once I chanded the backed url to localhost, then everything worked as expected

Angular authentication using Passport for Ionic App

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.

how to restrict only admin to add user?

Iam new to express.js. I got strucked with problem of adding user only by admin. and also user should not bee add if admin logged out. Here is my code please can any one help me. Iam using express.js, mongodb.
it is server side code
route.js
app.route('/auth/signin').post(users.signin);
app.route('/auth/adduser').post(users.in,users.adduser);
express.js
This is my signin code
exports.signin = function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err || !user) {
res.status(400).send(info);
} else {
// Remove sensitive data before login
user.password = undefined;
user.salt = undefined;
req.login(user, function(err) {
if (err) {
res.status(400).send(err);
} else {
req.session.value = user;
res.jsonp(user);
}
});
}
})(req, res, next);
};
This is adduser code
exports.in=function(req,res,next){
var user=req.session.value;
console.log('user details get from signin page'+JSON.stringify(user));
if(user.username===config.admin.username){
next(); //it goes to add user page
}
else{
res.send('your not a Admin');
}
};
exports.adduser = function(req, res) {
delete req.body.roles;
var user = new User(req.body);
var message = null;
// Add missing user fields
user.provider = 'local';
user.displayName = user.firstName + ' ' + user.lastName;
user.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(user);
console.log('user added');
}
});
};
But, while exceuting the code it gets error that req.session.value is undefined
i.e..,the data is not getting from signin page.
The main aim of posting this code is admin only has to add the user when he login .otherwise should send a message like you are not an admin or please login....
Actually passport sets the user on req object with logIn() method so you dont need this line
req.session.value = user; // remove this
and you can just get user on
console.log(req.user);
To verify this
Add this middleware in server.js or you app.js
app.use(function(req, res, next) {
console.log(req.user);
next();
});
here after the login occurs and authenticate plus logIn() methods are called , refreshing the page will console.log your user
Adding custom object/varaibles to session
to add user object or any thing else on session of passport you can do this as follow
req.session.passport.hi = "hello";
to verify this after adding this to session on subsequent page refresh see console when using following middleware
app.use(function(req, res, next) {
console.log(req.session.passport.hi);
next();
});

Resources