express-session vs passport.js? - node.js

I am currently implementing email-password login functionality for a website using just express-session. Everywhere I look I see people using passport.js to authenticate requests. The below code is working for me.
app.post("/signup", function(req, res) {
var user = new userModel(req.body);
user.save();
req.session.userid = user.id; // I use this id to authenticate
}
Do I have any reason to use passport?

In NodeJS, you can authenticate in 2 ways:
Session-Based authentication
Token-Based authentication
Passport is a token-based authentication system. It uses JSON web token i.e jwt.
In your case, as you are using session-based authentication you need not use passport

Related

Delegate authentication token from react app to express app with OpenID and passportjs

I am using the OpenID client to authenticate the user, what I would like to do is call a protected route on an express API.
I am trying to share the authorization cookie obtained with the react app with OpenID, and the xenter image description here
I tried:
simply passport.authenticate(), with the openID strategy, but does redirection which isnt necessary
Not sure if this is the correct way but, this is how I kinda did it:
const user = await auth0Client.getUser();
// Attach token
const accessToken = await auth0Client.getTokenSilently();
axios.defaults.headers.common.Authorization = `Bearer ${accessToken}`;
Then I just used the passport JWT strategy combined with jwks-rsa library to obtain the secret.

Handle Google OAuth with JWT (react + nodejs)

I am working on the authentication system of a web app, using Next.js for the client app and Node.js for the API.
I have my Next.js app on port 3000
I externalized the API of my application, on port 5000
That's why I used JWT for the local signin/signup strategies.
(I'm planning to use the same API for the mobile application later)
I am now wondering what is the best approch for a Google Authentication.
I have set it up, but I don't know how to give the token to the client.
Here is the process:
On Signin page (http://localhost:3000/signin), the user clicks on "Google authentication". It redirects to 'http://localhost:5000/auth/google"
Passport handles it, it redirects to Google OAuth page. User authorize the application.
Google redirects to the callback URL (http://localhost:5000/auth/google/redirect)
In the callback route, I can create a JWT. But how can I give it back to the client ?
I have thought of passing it through URL, but I am wondering if it is safe ?
Is there another way to do it / Am I missing the point ?
router.get('/google/redirect', (req, res, next) => {
return passport.authenticate('google', (err, user) => {
if (err) {
return res.redirect('http://localhost:3000/signin')
}
console.log(user)
// Create JWT and redirect to http://localhost:3000/signin/oauth?token=xxx ?
})(req, res, next)
})
I can show more code if needed, but it works (code is not the blocking point).
Thank you in advance !
all you have to do is setting up cookie session. When google sends responds to /google/redirect, passport.authenticate will call req.login() and this will call the serializeUser
passport.serializeUser(
(user, done ) => {
done(null, user.id); // stores the id<4kb
}
);
this function will create, passport:{user:userId}. this is the unique identifying information about the user. This where you need session. Because passport.js will automatically look for req.session and attaches the passport object to the req.session.
Since we are storing only userId, usually cookie-session package. this package will set req.session object, passport.js will attach the passport object and the cookie-session will store this on the client.

How to authenticate angular 10 client app from node/express js using passport-google strategy?

I'm building a web app that is being used on top of microservices architecture.
Using node/express js I have implemented auth service and products service both are listening on different ports like
http://localhost:8001 for authentication service
http://localhost:8002 for products service.
Kong Gateway used to authenticate and connect the microservices with jwt. Implemented passport-jwt and passport-local strategy to authenticate the users from client side using post calls.
Finally I have implemented the google auth on server side using passport-google strategy in this below URL
http://localhost:8001/auth/google -> it directs me to google auth consent screen after sign in it is redirecting to below Url
http://localhost:8001/auth/google/callback with token. it works fine at server end.
async googlecallback(req, res, next){
passport.authenticate('google', {
session: false,
}, (err, user, message) => {
if (!user) {
return next(new UnAuthorizedException(message))
}
const token = user.generateToken()
user = UserTransformer.transform(user)
user.token = token
this.Response(res, user, message) // sending response to client using custom method
})(req, res)
}
. When I come to authenticate the user from angular app client side. I'm unable to proceed further. just struggling here. :-(
How can I authenticate the user when they click google sign in button in angular 10 on client side?
My front end app Url like http://localhost:4002/account/login
Tried to use window.open("http://localhost:8001/auth/google","_blank") method, not working as expected.
res.setHeader('x-code', 'jwthere'); header method. Also tried to pass the JWT token with URL parameter. but both seems unsecure.
http://localhost:4002/account/login?token=7wF8bit5W1Pfi5Glt1X8H0YQu8BN7OeNRcX1zbj3AGpUHaYSxLlNIjHpzuw
security is the major concern here. I want the google sign in like khanacademy social login
https://www.khanacademy.org

Securing HTTP endpoint using service api

Below is the code, where I am trying to authenticate using third party providers. My authentication call is a service api which is running in different servers. How can authenticate users in my code
//app.js
app.use(passport.initialize());
// Create our Express router
var router = express.Router();
router.route('/test')
.get(**<first authenticate user using service api http://localhost:1000/authenticate>**, serviceController.getData);
app.listen(2000);
//authController.js
var app = express();
var router = express.Router();
router.post("/authenticate",function(req,res){
//Using third party providers like LDAP or Facebook using Passport
res.send("User authenticated");//Token will be send
});
app.listen(1000);
//authController.js - as function call it is working
var passport = require('passport');
var BasicStrategy = require('passport-http').BasicStrategy;
passport.use(new BasicStrategy(
function (username, password, callback) {
// Success
//return callback(null, true);
}
));
exports.isAuthenticated = passport.authenticate('basic', { session: false });
Is it possible to secure my api http://localhost:2000/test using LDAP or Facebook authentication. I am looking for something similar to SSO.
Expected result
When I hit http://localhost:2000/test, a request must be made to LDAP or facebook server running in http://localhost:1000/ to validate user and send the response from "User authenticated".
Any help on this will be really helpful.
there are couple of possibilities to achieve that using node.js
Passport Facebook; https://github.com/jaredhanson/passport-facebook
LDAP for node.js; http://ldapjs.org/
Passport provides plenty of different possibilities to login: twitter, google, facebook, linkedin, instagram. They are pretty easy to implement as well.
Check it here: http://passportjs.org/docs

NodeJS OAuth2.0 principles

Recently I was working on a nodeJS project and I was thinking how to go about and implement the security module of my mobile application. I had a previous experience from OAuth 2.0 protocol which I used in C# projects in the past.
In .NET there are two nice open source project
https://github.com/thinktecture/Thinktecture.IdentityServer.v3
https://github.com/thinktecture/Thinktecture.AuthorizationServer
The former is an Identity Provider supporting federated authentication and the later is an OAuth 2.0 provider.
So I decided to employ the same security infrastructure for my nodeJS app. But as far as I know, there is nothing equivalent to those projects.
I found some really nice project, which are not yet complete but are a good start:
https://www.npmjs.org/package/node-oauth2-server
https://github.com/domenic/restify-oauth2
In addition, I came across a nice article that suggests a nice way to deal with authentication in nodeJS. https://auth0.com/blog/2014/01/07/angularjs-authentication-with-cookies-vs-token/ and a similar answer to a questtion on stackoverflow. Auth between a website and self-owned API
From what I understood, expressJwt guards our api's and basically will validate the access token sent by the user. But I'd like to go a step further, and associate a token with app specific scopes, in a similar way that one would do with the OAuth2.0 protocol. So for example, I would like to assign a write, read etc. scopes and have expressJwt check if the user's token has the required scopes to access as specific API endpoint.
I would be grateful if you could provide me with some suggestions about how to deal with this topic.
First, you need to generate a token with such claims. This could be in an API or some other place:
var jwt = require('jsonwebtoken');
var claims = {
name: user.name
can_write: true,
can_post_timeline: false
};
var token = jwt.sign(claims, 'my-super-secret');
Then, to validate you will do something like this:
var jwt = require('express-jwt');
app.use(jwt({secret: 'my-super-secret'}));
function require_time_line_access (req, res, next) {
if (!req.user.can_post_timeline) return res.send(401);
next();
}
app.post('/timeline',
require_time_line_access,
function(req, res) {
//do timeline stuff
});
express-jwt validates the signature of the token, expiration and few other things. If everything is okay it puts the decoded token in req.user, and if is not okay it returns 401.
require_time_line_access is a middleware that ensure the user has this claim, if it doesnt it returns 401. You can put this middleware in every endpoint that needs this claim.

Resources