JSON WEB Authentication with Angular 8 and NodeJS

栏目: IT技术 · 发布时间: 4年前

内容简介: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;JSON Web
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.

JSON WEB Authentication with Angular 8 and NodeJS

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:

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.

JSON WEB Authentication with Angular 8 and NodeJS

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.

JSON WEB Authentication with Angular 8 and NodeJS

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 Authentication with Angular 8 and NodeJS

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.

JSON WEB Authentication with Angular 8 and NodeJS

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


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Spring揭秘

Spring揭秘

王福强 / 人民邮电出版社 / 2009.8 / 99.00元

没有教程似的训导,更多的是说故事般的娓娓道来,本书是作者在多年的工作中积累的第一手Spring框架使用经验的总结,深入剖析了Spring框架各个模块的功能、出现的背景、设计理念和设计原理,揭开了Spring框架的神秘面纱,使你“知其然,更知其所以然”。每部分的扩展篇帮助读者活学活用Spring框架的方方面面,同时可以触类旁通,衍生出新的思路和解决方案。 本书内容全面,论述深刻入理,必将成为每......一起来看看 《Spring揭秘》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具