Passport Authentication User Login Example in Node Js.

Passport Authentication User Login Example in Node Js.

In this article, we will share with you how to make users login authentication system in node js using a passport.

In this article i will share with you how to make user login authentication system in node js using passport.

How To Create Authentication in Angular with Nodejs and Passport.js

How To Create Authentication in Angular with Nodejs and Passport.js

In this tutorial, you'll learn how to build an authentication in your Node Angular app using Passport.js.

In this tutorial, you'll learn how to build an authentication in your Node Angular app using Passport.js.

The tutorial assumes the reader to be familiar with creating a basic application using Angular and Node.js Express framework. You'll implement the Authentication using Passport on top of an Angular Sales Dashboard application covered in a previous tutorial.

The source code from this tutorial is available on GitHub.

Why Authentication?

Why do you need authentication? Well, adding some kind of authentication makes your application secure and prevents unauthorized access.

Authentication can be done with a username and password or it can be a One-Time Password (OTP) sent to your phone. Using existing user information from popular social networks such as Google, Facebook, etc. is another way to add authentication.

What is Passport.js?

Passport.js is a middleware that can be easily used in your Node.js application. It helps to authenticate using username and password, Facebook, GitHub, etc.

From the official documentation,

Passport is authentication middleware for Node.js. Extremely flexible and modular, Passport can be unobtrusively dropped into any Express-based web application. A comprehensive set of strategies support authentication using a username and password, Facebook, Twitter and more.

Getting Started

Let' start by cloning the source code of the Angular Sales Dashboard app from its GitHub repository.

git clone https://github.com/JscramblerBlog/angular_dashboard

Navigate to the project directory and install the required dependencies.

cd angular_dashboard
npm install

Once the dependencies have been installed, start the Angular application server.

npm start

You'll have the Angular application running on localhost:4200.

Setting Up Authentication API

To set up the authentication API, you need to create a Node project.

mkdir node-api
cd node-api
npm init

Enter the required details and you will have the Node project setup. Next, install the Express framework for creating the API.

npm install express --save

Once you have Express installed, create a file called app.js and add the following code to it:

const express = require('express');
const app = new express();

app.post('/authenticate', (req, res) => {
    res.status(200).json({"statusCode" : 200 ,"message" : "hello"});
});

app.listen(3000, () => {
    console.log('App running at 3000')
})

That's the basic Express server with an endpoint. You now need to add a custom middleware to the /authenticate route.

What is a Middleware?

A middleware is a function that can intercept a request. It has access to the request, response objects and a next function. This next function, when invoked, executes the next middleware.

Let's add a custom middleware to the route.

const auth = () => {
    return (req, res, next) => {
        next()
    }
}

app.post('/authenticate', auth() , (req, res) => {
    res.status(200).json({"statusCode" : 200 ,"message" : "hello"});
});

The auth custom middleware does nothing but invoke the next middleware by calling next. Inside the auth middleware, you'll authenticate the user using Passport.

To use Passport, you need to install both passport and passport-local.

npm install passport --save
npm install passport-local --save

You'll be using the passport-local strategy to authenticate the user login using a username and password.

Require both passport and passport-local in app.js.

const  passport  =  require('passport');
const  LocalStrategy  =  require('passport-local').Strategy;

Passport has a number of strategies when it comes to authentication. You'll be using the local strategy in this tutorial and so we need to define it as below.

passport.use(new LocalStrategy(
    function(username, password, done) {
        if(username === "admin" && password === "admin"){
            return done(null, username);
        } else {
            return done("unauthorized access", false);
        }
    }
));

The local strategy uses the username and password for authentication. For the sake of this tutorial, we have hardcoded the username and password check.

Before getting into the detailed code, let's have a look at how the Passport authentication executes.

  • A request is received at the authenticate route.
  • The custom middleware intercepts the request and makes the Passport authentication call.
  • On successful authentication, Passport stores the user data in the session.
  • On subsequent requests, Passport fetches the user data from the session for authentication.

Let's make the Passport authentication call inside the custom middleware auth.

const auth = () => {
    return (req, res, next) => {
        passport.authenticate('local', (error, user, info) => {
            if(error) res.status(400).json({"statusCode" : 200 ,"message" : error});
            req.login(user, function(error) {
                if (error) return next(error);
                next();
            });
        })(req, res, next);
    }
}

passport.authenticate invokes the passport-local strategy and, once authentication is done, the callback is invoked.

On successful authentication, Passport saves the user data in the session. For that to happen, you need to invoke req.login with the user object.

You also need to define the serialize and deserialize method to facilitate user data storage in the session and retrieving the data on subsequent requests.

passport.serializeUser(function(user, done) {
    if(user) done(null, user);
});

passport.deserializeUser(function(id, done) {
    done(null, id);
});

Let’s now install and use the body-parser middleware so that the app can parse the posted parameters.

npm install body-parser --save

To use Passport, you need to initialize it and use it as below.

app.use(passport.initialize());
app.use(passport.session());

To authenticate subsequent requests, you can define another middleware function. This function checks if the user data exists in the request. passport provides a method called req.isAuthenticaed which can be used to check if the user is authenticated.

Here is how the middleware function looks:

const isLoggedIn = (req, res, next) => {
    if(req.isAuthenticated()){
        return next()
    }
    return res.status(400).json({"statusCode" : 400, "message" : "not authenticated"})
}

You can use the above middleware on other routes as shown below:

app.get('/getData', isLoggedIn, (req, res) => {
    res.json("data")
})

Let's move on to adding the authentication to the Angular Dashboard app.

Authenticating the Angular App

To add authentication to the Angular dashboard app, you need to add routes to the Angular application. From the project directory, execute the following command:

ng generate module app-routing --flat --module=app

It should create the routing module. Open app-module.routing.ts and replace it with the following code:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';

const routes: Routes = [
  { path: 'home', component: AppComponent },
  { path: 'login', component : LoginComponent}
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

You'll be using two additional components in the Angular app called the login and root component. The LoginComponent will handle the login functionality and RootComponent will serve as the container for rendering different views.

ng generate component login
ng generate component root

Adding Route Guard To The Home Route

To authenticate the Angular route from any unauthorized access, you'll be adding a route guard. The guard uses an authorization service to check if the route access is authenticated.
Let's create an authorization service to check is access is authenticated.

ng generate service auth

The above command creates a service called auth.service.ts. Add the following code to it:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  constructor(private http : HttpClient) { }

  public isAuthenticated() : Boolean {
    let userData = localStorage.getItem('userInfo')
    if(userData && JSON.parse(userData)){
      return true;
    }
    return false;
  }

  public setUserInfo(user){
    localStorage.setItem('userInfo', JSON.stringify(user));
  }

  public validate(email, password) {
    return this.http.post('/api/authenticate', {'username' : email, 'password' : password}).toPromise()
  }
}

After validating the user login, AuthService saves the user information. It exposes a method called isAuthenticated which can be utilized by the AuthGuardService service to authenticate the route.

Let's create AuthGuardService.

ng generate service authGuard

Add the following code to the auth-guard.service.ts file.

import { Injectable } from '@angular/core';
import { CanActivate,Router } from '@angular/router';
import {AuthService} from './auth.service';

@Injectable({
  providedIn: 'root'
})
export class AuthGuardService implements CanActivate {

  constructor(private authService : AuthService, private route : Router) { }

  canActivate(){
    if(this.authService.isAuthenticated()){
      return true;
    }
    this.route.navigate(['login']);
    return false;
  }
}	

The above AuthGuardService implements the CanActivate route guard. It means that, if the guard returns true, the navigation will continue; otherwise, it navigates to login.

Let's add the route guard to the home route in app-routing.module.ts.

const routes: Routes = [
  { path: 'home', component: AppComponent, canActivate : [AuthGuard] },
  { path: 'login', component : LoginComponent}
];

Inside the Login component, on click you need to make the API call the Node authentication API. Here is how the login.component.ts file looks:

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../auth.service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  userEmail : String;
  userPassword : String;

  constructor(private authService : AuthService, private router : Router) { }

  ngOnInit() {

  }

  login(){
    this.authService.validate(this.userEmail, this.userPassword)
    .then((response) => {
      this.authService.setUserInfo({'user' : response['user']});
      this.router.navigate(['home']);

    })
  }

}

For the API call to work from Angular to Node, you need to add a proxy conf file in the Angular app. Create a file called proxy.conf.json and add the following code :

{
    "/api/*": {
      "target": "http://localhost:3000",
      "pathRewrite": {"^/api" : ""}
    }
  }

Save the above changes and run the Angular app along with the Node REST API. Open the localhost:4200/home route and you will be redirected to the login screen. Once there, enter the credentials as admin and admin and you will be redirected to the Angular dashboard screen.

Wrapping it Up

In this tutorial, you learned how to authenticate a REST API using Passport. You also learned how to authenticate the Angular routes using route guards.

You used the passport-local strategy to implement authentication. In addition to passport-local, there a number of other Passport strategies for authentication.

**Finally, don't forget to pay special attention if you're developing commercial Angular apps that contain sensitive logic.

Thank you for reading !

Top Collection NodeJS Frameworks for Developers in 2020

Top Collection NodeJS Frameworks for Developers in 2020

Node.js is an open-source, cross-platform runtime environment built on Chrome’s V8 javascript engine. The event-driven, non-blocking I/O model makes the NodeJS framework an extremely lightweight and efficient web application.

Node.js is an open-source, cross-platform runtime environment built on Chrome’s V8 javascript engine. The event-driven, non-blocking I/O model makes the NodeJS framework an extremely lightweight and efficient web application.

As a developer, one gets to smoothly use the same language for both client–side and server–side scripting and this unique facility has increased the quick adoption of NodeJS frameworks by many developers across the globe in building web applications of any size.

Since it’s been launched in 2009 as a tool for building scalable, server-side web applications it has brought about exponential growth in its usage.

In addition, Node facilitates quick prototyping in building unique projects.

Let’s check out this list of 10 Top NodeJS Frameworks:

1. Hapi.JS

Hapi is a powerful and robust framework that is used for developing APIs. The well-developed plugin system and various key features such as input validation, configuration-based functionality, implement caching, error handling, logging, etc. make the Hapi one of the most preferred frameworks. It is used for building useful applications and providing technology solutions by several large-scale websites such as PayPal, Disney.

Hapi builds secure, powerful, and scalable applications with minimal overhead and out-of-the-box functionality

Hapi is a configuration-driven model built to control web server operations. It has the unique function of being able to create a server on a specific IP , and has functions such as " onPreHandler ", we can process the request by intercepting the request and preprocessing the request before it is completed.

2. Express.JS

Express.js was built by TJ Holowaychuk, one of the members of the core Node project team. A large community backs this framework, so it has the advantages of continuous updates and reforms of all the core features. This is a minimalist framework that is used to build a number of mobile applications and APIs.

Express is a minimal and flexible Node.JS web application framework providing a robust set of features

It’s robust API allows users to configure routes to send/receive requests between the front-end and the database (acting as a HTTP server framework).

A good advantage with express is how it supports a lot of other packages and other template engines such as Pug, Mustache, EJS and a lot more.

3. Socket.io

It is used for building real-time web applications. It’s a Javascript library that allows the bidirectional data flow between the web client and server. Asynchronous data I/O, binary streaming, instant messaging are some of the most important features of this framework.


Socket the fastest and reliable real-time engine

4. Total.JS

Total.js is a modern and modular NodeJS supporting the MVC architecture. Angular.js, Polymer, Backbone.js, Bootstrap and other client–side frameworks are fully compatible with this framework. This framework is totally extensible and asynchronous. The fact that it does not require any tools such as Grunt to compress makes it easy to use. It also has NoSql embedded in it and supports array and other prototypes.

Total.js has some really beautiful versions like the Total.js Eshop, which contains a user interface optimized for mobile devices, and it is downloadable by all premium members. Eshop is one of the best Node.js e-commerce system. This is because of its many versions of unique content management system(CMS).

5. Sail.JS

This MVC framework has become very popular with NodeJS developers and this framework has gained traction through the development of chat applications, dashboards and multiplayer games. It is most famous for building data-driven APIs. It uses waterline for object-related mapping and db solutions. This framework uses Express.js for handling HTTP requests and is built upon Node.js.

Its compatibility with Grunt modules, including LESS, SASS, Stylus, CoffeeScript, Jade, Dust makes it an ideal candidate for browser-based applications.

Sail is highly compatible with several front-end platforms. Developers have enough freedom to their development while implementing this framework.

6. Derby

This is an MVC framework that is used for creating real-time mobile and web applications. Derby’s Racer, a real-time data synchronization engine for Node.js allows multi-site, real-time concurrency and data synchronization across clients and servers. The racer optimizes conflict resolution and allows real-time editing of the application by leveraging the ShareJS.

Derby is a full-stack framework for writing modern web applications

Derby is an open-source framework based on MVC structure and it is a full-stack NodeJS web framework. Derby is considered ideal for developing real-time collective applications. Using DerbyJS , developers can easily add customized codes and build real-time and effective custom made websites.

7. Meteor.JS

One of the fundamentally most used NodeJS frameworks is Meteor.JS. And this list would remain incomplete if we didn’t mention the MeteorJS framework. This is a full-stack framework of NodeJS which allows users to build real-time applications.

It is used to create both mobile and web-based javascript applications.

Backed by a huge community of developers, tutorials, custom packages and documentation, this framework is used to create some great web and mobile applications for only Javascript only.

8. Loopback

Loopback is a highly-extensible API framework that allows the user to create such APIs that can work with any kind of web client and can be easily bridged to backend sources. This new age modern application comes with complex integration. With Loopback being an open-source framework, the user can create dynamic REST APIs with a minimum or no knowledge of coding.

Highly extensible NodeJS framework for building APIs and microservices

Loopback permits developers to create SDKs and API documentation. This is possible due to widget-API explorer that comes in default with loopback.

Also, it comes with model-relation-support, third party login and storage service, API swagger, better user management policy

9. Koa

Koa was created by the same team that created Express.js and it is often referred to as the next-generation NodeJS framework. Koa is unique in the fact that it uses some really cool ECMAScript(ES6) methods that have not even landed in some browsers yet. It allows you to work without callbacks while providing you with an immense increase in error handling.

It requires a NodeJS version of at least 0.11 or higher.

KoaJS supports syn/await keywords and helps to manage the codes neatly.

Also, it doesn’t pack any bundle of middleware in the core. That makes server writing with Koa faster and enjoyable. KoaJS comes with more options for customization. It allows you to work with applications from scratch where developers can add those features only which they need.

10. NestJS

NestJs is a framework built with Node.js, It is used for building efficient, scalable Node.js server-side applications. Nest uses progressive JavaScript and is written with TypeScript. Being built with TypeScript means that Nest comes with strong typing and combines elements of OOP(Object Oriented Programming), FP(Functional Programming) and FRP(Functional Reactive Programming).

Advantages of the NodeJS framework

NodeJS Framework is now emerging as the most commonly used development framework for building frontend and backend for web applications. And it is the most preferred environment for custom web development. Let’s check some of the major advantages of NodeJS Framework:

  • Real-time working environment
  • Simple coding experience
  • Seamless data streaming
  • Same code pattern throughout development
  • User-friendly
Final analysis

After reading this article, we can of course understand that which framework to use depends entirely on the type of website and web application we want to build. The list of frames is endless and is everywhere in the JavaScript community.

All you need to know about NodeJS Development (FAQ)

All you need to know about NodeJS Development (FAQ)

NodeJS Development FAQ: What is Nodejs, features of Nodejs, Nodejs modules, Types of API functions in Nodejs, Role of REPL in Nodejs, Benefits of nodejs, Difference between Angular JS and Node JS

Did you know that top businesses like #Netflix, #Reddit, #eBay, #Slack and #twitter all use NodeJS? Hosting Tribunal has also enumerated that a cool 85% use #NodeJS for #webappdevelopment. Here All you need to know about #NodeJSDevelopment (FAQ)-