paint-brush
JSON Web Auth Using Angular 8 and NodeJSby@th3n00bc0d3r
300 reads
300 reads

JSON Web Auth Using Angular 8 and NodeJS

by Muhammad BilalNovember 22nd, 2020
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

The Backend will be running on Node.JS. The security that will underlay the interfacing will be JSON Web Tokens. An interceptor is a service that will break any requests sent from Angular, clone it and add a token to it before it is finally sent. In the interceptor of the Angular App, all requests will be checked for a 401 status and upon receiving such a request, the token stored at Angular will be removed and the user will be logged out of all sessions, sending him to the login screen.

People Mentioned

Mention Thumbnail
featured image - JSON Web Auth Using Angular 8 and NodeJS
Muhammad Bilal HackerNoon profile picture

The article is about interfacing an Angular 8 Project with a secure backend API. The Backend will be running on Node.JS. The security that will underlay the interfacing will be JSON Web Tokens.

At the end of the article, you should have learned to;

What is JSON Web Tokens?

JSON Web Token is an RFC Standard (Request for Comments) https://tools.ietf.org/html/rfc7519. The RFC Standard is a best-practice set of methodologies. It takes in a JSON object and encrypts it using a secret key that you set, HMAC algorithm, or a public/private key pair that can be generated using RSA or ECDSA. For this tutorial, we will be using a secret key.

Why use JSON Web Tokens?

It is a secure way to verify the integrity of the exchange of information between the client and the server. We will adapt it for authorisation so that in case of any breach, the token will not verify or expire based on time.

Theory in Practice

We will be using Angular on the frontend and a Node.JS server on the backend. On the Angular side of things, an interceptor will be created. An interceptor is a service that will break any HTTP Request sent from Angular, clone it and add a token to it before it is finally sent. On the Node.JS side of things, all requests received will first be broken and cloned. The token will be extracted and verified. In case of successful verification, the request will be sent to its handler to send a response and in the case of an unsuccessful verification, all further requests will be canceled and a 401 Unauthorized status will be sent to Angular. In the interceptor of the Angular App, all requests will be checked for a 401 status and upon receiving such a request, the token stored at Angular will be removed and the user will be logged out of all sessions, sending him to the login screen.

Let’s create the Angular App:

ng new angFrontend

Now let’s create our Interceptor:

ng generate service AuthInterceptor

Now go to src/app/app.module.ts

We will be importing the HTTP Module for HTTP Calls and making our interceptor as a provider so it has global access to all HTTP Calls.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';
import { AuthInterceptorService } from './auth-interceptor.service';
import { HomeComponent } from './home/home.component';

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,

    HttpClientModule
  ],
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptorService, multi: true }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Now let’s open the interceptor service class:

Now go to src/app/auth-interceptor.service.ts:

import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse } from '@angular/common/http';
import { catchError, filter, take, switchMap } from "rxjs/operators";
import { Observable, throwError } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class AuthInterceptorService implements HttpInterceptor {


  intercept(req: HttpRequest<any>, next: HttpHandler) {
    console.log("Interception In Progress"); //SECTION 1
    const token: string = localStorage.getItem('token');
    req = req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + token) });
    req = req.clone({ headers: req.headers.set('Content-Type', 'application/json') });
    req = req.clone({ headers: req.headers.set('Accept', 'application/json') });

    return next.handle(req)
        .pipe(
           catchError((error: HttpErrorResponse) => {
                //401 UNAUTHORIZED - SECTION 2
                if (error && error.status === 401) {
                    console.log("ERROR 401 UNAUTHORIZED")
                }
                const err = error.error.message || error.statusText;
                return throwError(error);                    
           })
        );
  }  
}

Section 1

As in authentication, the token we get from the server will be stored in the local storage, therefore first we retrieve the token from local storage. Then the httpRequest req is cloned and a header of “Authorisation, Bearer: token” is added to it. This token will be sent in the header of the httpRequest. This method can also be used to standardised all the requests with the Content Type and Accept header injection too.

Section 2

In case of an error response or error status such as 401, 402 and so on so forth, the pipe helps to catch the error and further logic to de-authenticate the user due to a bad request (Unauthorised Request) can be implemented here. In the case of other error requests, it simply returns the error in the call to the frontend.

Great, now let’s create the Backend.

Create a Directory for the Server and type in npm init to initialize it as a node project:

mkdir node_server
cd node_server
npm init -y

Use the following command to install the required libraries:

npm i -S express cors body-parser express-jwt jsonwebtoken

Let’s create an app.js in the node_server folder and start coding the backend.

Now, this is app.js and the boilerplate code:

const express       = require('express')
const bodyParser    = require('body-parser');
const cors          = require('cors');

const app           = express();
const port          = 3000;

app.use(cors());
app.options('*', cors());
app.use(bodyParser.json({limit: '10mb', extended: true}));
app.use(bodyParser.urlencoded({limit: '10mb', extended: true}));

app.get('/', (req, res) => {
    res.json("Hello World");
});

/* CODE IN BETWEEN */

/* CODE IN BETWEEN */

/* LISTEN */
app.listen(port, function() {
    console.log("Listening to " + port);
});

Now we need to have a route where the token is generated, usually, in a production app, this route will be where you will be authenticating the user, the login route, once successfully authenticated, you will send the token.

//SECRET FOR JSON WEB TOKEN
let secret = 'some_secret';

/* CREATE TOKEN FOR USE */
app.get('/token/sign', (req, res) => {
    var userData = {
        "name": "Muhammad Bilal",
        "id": "4321"
    }
    let token = jwt.sign(userData, secret, { expiresIn: '15s'})
    res.status(200).json({"token": token});
});

So now we have a route, a secret for encoding our data and remember a data object i.e userData. Therefore, once your decode it, you will get back to this object, so storing a password is not a good practice here, maybe just name and id.

Now let’s run the application and check token generated:

node app.js
Listening to 3000

We will be using postman to test our routes, great tool, I must say.

As you can see, we have successfully generated our first web token.

To illustrate a use case, we have just created a path1 and I want to secure this endpoint using my JSON Web Token. For this, I am going to use express-jwt.

app.get('/path1', (req, res) => {
    res.status(200)
        .json({
            "success": true,
            "msg": "Secrect Access Granted"
        });
});

Express-JWT in motion.

//ALLOW PATHS WITHOUT TOKEN AUTHENTICATION
app.use(expressJWT({ secret: secret})
    .unless(
        { path: [
            '/token/sign'
        ]}
    ));

To further illustrate the code, it states that only allow these paths to access the endpoint without token authentication.

Now in the next step, we will try to access the path without a token sent in the header.

As you can see, it didn’t allow us to access the path. It also sent back a 401 Unauthorized, so that’s great. Now let’s test it with the token we obtained from the token/sign route.

app.get('/path1', (req, res) => {
    res.status(200)
        .json({
            "success": true,
            "msg": "Secret Access Granted"
        });
});

As you can see, when adding the Bearer Token, we have successfully gotten access to it. Heading back to angular, I just created a new component home

ng generate component home

Now this is my home.component.ts file

  signIn() {
    this.http.get(this.API_URL + '/token/sign')
      .subscribe(
        (res) => {
          console.log(res);
          if (res['token']) {
            localStorage.setItem('token', res['token']);
          }
        },
        (err) => {
          console.log(err);
        }
      );    
  }

  getPath() {
    this.http.get(this.API_URL + '/path1')    
      .subscribe(
        (res) => {
          console.log(res);
        },
        (err) => {
          console.log(err);
        }
      );       
  }

So simply, on the signIn function, I am requesting a token and storing it into localstorage and then on the second function, I am requesting the path.

Now when I run the application, this is a response, I am expecting. Now I am going to refresh, so I can lose the localstorage token, and then try to access the path.

As you can see, we have successfully gotten a 401 Unauthorized, therefore our application is secured.

Conclusion

We have successfully secured our service and all communication between the two parties using JSON Web Tokens. This article has helped us in taking an overview of implementing the JWT in both Angular 8 and Node.JS. I hope this contribution will help you in securing your applications and taking a step towards making it production-ready.

Github Repo

https://github.com/th3n00bc0d3r/Json-Web-Token-Authentication-with-Angular-8-and-Node-JS

Previously published at https://soshace.com/json-web-authentication-with-angular-8-and-nodejs/