Close Menu
Soshace Digital Blog

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    What's Hot
    Beginners

    Understanding Data Structures in JavaScript (Linked Lists)

    JavaScript

    Introduction to Micro Frontends: The New Tech on the Block

    Angular

    Handling HEIC Images in Angular: A Comprehensive Tutorial

    Important Pages:
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Today's Picks:
    • Scaling Success: Monitoring Indexation of Programmatic SEO Content
    • Leveraging Influencers: Key Drivers in New Product Launches
    • How Privacy-First Marketing Will Transform the Industry Landscape
    • The Impact of Social Proof on Thought Leadership Marketing
    • Balancing Value-Driven Content and Promotional Messaging Strategies
    • Top Influencer Marketing Platforms to Explore in 2025
    • Emerging Trends in Marketing Automation and AI Tools for 2023
    • Strategies to Mitigate Duplicate Content in Programmatic SEO
    Wednesday, September 10
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Soshace Digital Blog
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Services
    • SaaS & Tech

      Maximizing Efficiency: How SaaS Lowers IT Infrastructure Costs

      August 27, 2025

      Navigating Tomorrow: Innovations Shaping the Future of SaaS

      August 27, 2025

      Maximizing Impact: Strategies for SaaS & Technology Marketing

      August 27, 2025
    • AI & Automation

      Enhancing Customer Feedback Analysis Through AI Innovations

      August 27, 2025

      Navigating the Impact of AI on SEO and Search Rankings

      August 27, 2025

      5 Automation Hacks Every Home Service Business Needs to Know

      May 3, 2025
    • Finance & Fintech

      Critical Missteps in Finance Marketing: What to Avoid

      August 27, 2025

      Analyzing Future Fintech Marketing Trends: Insights Ahead

      August 27, 2025

      Navigating the Complex Landscape of Finance and Fintech Marketing

      August 27, 2025
    • Legal & Compliance

      Exploring Thought Leadership’s Impact on Legal Marketing

      August 27, 2025

      Maximizing LinkedIn: Strategies for Legal and Compliance Marketing

      August 27, 2025

      Why Transparency Matters in Legal Advertising Practices

      August 27, 2025
    • Medical Marketing

      Enhancing Online Reputation Management in Hospitals: A Guide

      August 27, 2025

      Analyzing Emerging Trends in Health and Medical Marketing

      August 27, 2025

      Exploring Innovative Content Ideas for Wellness Blogs and Clinics

      August 27, 2025
    • E-commerce & Retail

      Strategic Seasonal Campaign Concepts for Online and Retail Markets

      August 27, 2025

      Emerging Trends in E-commerce and Retail Marketing Strategies

      August 27, 2025

      Maximizing Revenue: The Advantages of Affiliate Marketing for E-Commerce

      August 27, 2025
    • Influencer & Community

      Leveraging Influencers: Key Drivers in New Product Launches

      August 27, 2025

      Top Influencer Marketing Platforms to Explore in 2025

      August 27, 2025

      Key Strategies for Successful Influencer Partnership Negotiations

      August 27, 2025
    • Content & Leadership

      The Impact of Social Proof on Thought Leadership Marketing

      August 27, 2025

      Balancing Value-Driven Content and Promotional Messaging Strategies

      August 27, 2025

      Analyzing Storytelling’s Impact on Content Marketing Effectiveness

      August 27, 2025
    • SEO & Analytics

      Scaling Success: Monitoring Indexation of Programmatic SEO Content

      August 27, 2025

      Strategies to Mitigate Duplicate Content in Programmatic SEO

      August 27, 2025

      Effective Data Visualization Techniques for SEO Reporting

      August 27, 2025
    • Marketing Trends

      How Privacy-First Marketing Will Transform the Industry Landscape

      August 27, 2025

      Emerging Trends in Marketing Automation and AI Tools for 2023

      August 27, 2025

      Maximizing ROI: Key Trends in Paid Social Advertising

      August 27, 2025
    Soshace Digital Blog
    Blog / Programming / JSON WEB Authentication with Angular 8 and NodeJS
    JavaScript

    JSON WEB Authentication with Angular 8 and NodeJS

    Muhammad BilalBy Muhammad BilalOctober 4, 2019Updated:December 4, 2019No Comments8 Mins Read
    Facebook Twitter Pinterest Telegram LinkedIn Tumblr Email Reddit
    JSON WEB Authentication with Angular 8 and NodeJS
    JSON WEB Authentication with Angular 8 and NodeJS
    Share
    Facebook Twitter LinkedIn Pinterest Email Copy Link
    JSON WEB Authentication with Angular 8 and NodeJS
    JSON WEB Authentication with Angular 8 and NodeJS

    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;

    • Create JSON Web Token after Authentication
    • Secure API Endpoints with JSON Web Tokens
    • Integrate JSON Web Tokens in Angular 8
    • Store and Retrieve a JSON Web Token
    • Implement an Interceptor/Middleware in Angular 8 and Node.JS
    • Implement a Status 401 Unauthorised Code

    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.

    Why use JSON Web Tokens?
    Why use JSON Web Tokens?

    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:

    Read More:  Create a Simple POS with React, Node and MongoDB #0: Initial Setup Frontend and Backend

    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});
    });

     

    Read More:  Top 3 Myths About Remote Web Developers

    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.

    Token generation
    Token generation

    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.

    Accessing the path without a token
    Accessing the path without a token

    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.

    JSON Web Test
    JSON Web Test

    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.

    Last step: secure app
    Last step: secure app

    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: https://github.com/th3n00bc0d3r/Json-Web-Token-Authentication-with-Angular-8-and-Node-JS

     

    JavaScript json node app nodejs security web developer web-development
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Muhammad Bilal

      Related Posts

      Mastering REST APIs: Essential Techniques for Programmers

      December 18, 2024

      Streamlining Resource Allocation for Enhanced Project Success

      December 18, 2024

      Crafting Interactive User Interfaces Using JavaScript Techniques

      December 17, 2024
      Leave A Reply Cancel Reply

      You must be logged in to post a comment.

      Stay In Touch
      • Facebook
      • Twitter
      • Pinterest
      • Instagram
      • YouTube
      • Vimeo
      Don't Miss
      React Native December 15, 2020

      Build Real-World React Native App #7: Send Feedback with Formik, Yup, Firebase Cloud Function and Sendgrid

      In this chapter, we will create a simple form in the Feedback.js file using Formik…

      Create simple POS with React.js, Node.js, and MongoDB #17: Stat screen

      October 23, 2020

      Strategies for Overcoming Prospecting Objections on LinkedIn

      December 9, 2024

      3. Express.js Lessons. Templating with EJS: Layout, Block, Partials

      December 16, 2016

      Categories

      • AI & Automation
      • Angular
      • ASP.NET
      • AWS
      • B2B Leads
      • Beginners
      • Blogs
      • Business Growth
      • Case Studies
      • Comics
      • Consultation
      • Content & Leadership
      • CSS
      • Development
      • Django
      • E-commerce & Retail
      • Entrepreneurs
      • Entrepreneurship
      • Events
      • Express.js
      • Facebook Ads
      • Finance & Fintech
      • Flask
      • Flutter
      • Franchising
      • Funnel Strategy
      • Git
      • GraphQL
      • Home Services Marketing
      • Influencer & Community
      • Interview
      • Java
      • Java Spring
      • JavaScript
      • Job
      • Laravel
      • Lead Generation
      • Legal & Compliance
      • LinkedIn
      • Machine Learning
      • Marketing Trends
      • Medical Marketing
      • MSP Lead Generation
      • MSP Marketing
      • NestJS
      • Next.js
      • Node.js
      • Node.js Lessons
      • Paid Advertising
      • PHP
      • Podcasts
      • POS Tutorial
      • Programming
      • Programming
      • Python
      • React
      • React Lessons
      • React Native
      • React Native Lessons
      • Recruitment
      • Remote Job
      • SaaS & Tech
      • SEO & Analytics
      • Soshace
      • Startups
      • Swarm Intelligence
      • Tips
      • Trends
      • Vue
      • Wiki
      • WordPress
      Top Posts

      Visualizing Logs from a Dockerized Node Application Using the Elastic Stack

      JavaScript January 30, 2020

      Mapping the World: Creating Beautiful Maps and Populating them with Data using D3.js 

      JavaScript January 21, 2020

      Mastering LinkedIn Lead Generation: Strategies for Success

      LinkedIn November 30, 2024

      Mastering JavaScript Proxies: Practical Use Cases and Real-World Applications

      Express.js May 7, 2023

      Subscribe to Updates

      Get The Latest News, Updates, And Amazing Offers

      About Us
      About Us

      Soshace Digital delivers comprehensive web design and development solutions tailored to your business objectives. Your website will be meticulously designed and developed by our team of seasoned professionals, who combine creative expertise with technical excellence to transform your vision into a high-impact, user-centric digital experience that elevates your brand and drives measurable results.

      7901 4th St N, Suite 28690
      Saint Petersburg, FL 33702-4305
      Phone: 1(877)SOSHACE

      Facebook X (Twitter) Instagram Pinterest YouTube LinkedIn
      Our Picks
      JavaScript

      Growth Hacking 101: Everything You Always Wanted to Know with Examples | 2019

      Programming

      DigitalOcean vs. AWS: Comparing Offers and Choosing the Better Option

      JavaScript

      How And When To Debounce And Throttle In React

      Most Popular

      Essential Strategies for Effective Technical Interview Preparation

      Interview

      Profiling Tools and Techniques for Node.js Applications

      Express.js

      Flask Development Made Easy: A Comprehensive Guide to Test-Driven Development

      Flask
      © 2025 Soshace Digital.
      • Home
      • About
      • Services
      • Contact Us
      • Privacy Policy
      • Terms & Conditions

      Type above and press Enter to search. Press Esc to cancel.