Introduction
This article discusses the JSON Web Token (JWT) and its authentication into your Angular 8 project with a secure backend API running on Node.JS. The security that will lie beneath the interfacing will be JWT as it is a secure and competent way to authenticate users using API endpoints.
What are JSON web tokens?
JSON Web Token is an open standard or RFC Standard (Request for Comments). It comprises a best-practice set of methodologies that describes a compact and autonomous way for securely transmitting information between parties as a JSON object. This information is digitally signed or encrypted and hence it can be simply verified and trusted. For this purpose, a secret key such as an HMAC algorithm is set or a public/private key pair is generated using RSA or ECDSA.
Why are JSON web tokens useful?
JWT offers the most secure way for authenticating the integrity of the exchange of information between the client and the server. It is adapted for verification so in the case of any violation or breach, the token will not verify or expire based on time.
Moreover, the benefits of JSON Web Tokens (JWT) outweigh more compared to Simple Web Tokens (SWT) or Security Assertion Markup Language Tokens (SAML) so JWT
can be preferred over the other two.
Let's take a glance at the theory in practice for JSON web authentication using Angular 8 and NodeJS.
Here, Angular 8 will be used on the frontend while the Node.JS server on the backend. First, an interceptor will be formed on the Angular side. An interceptor can break any HTTP request sent from Angular, replicate it, and insert a token to it before it is sent at last.
All the requests obtained will first be broken and replicated or cloned on the Node.JS side. Then, the token will be extracted and authenticated. If the verification is successful, the request will be forwarded to its handler for a specific response. If the authentication fails, all remaining requests will be invalid and a 401 unauthorized status will be sent to Angular.
All requests will be verified for a 401 status in the interceptor of the Angular App and for such a request, the token will be removed which is stored at Angular. The user will be logged out of all sessions and will land on the login screen.
Let’s get started.
The Angular App is created at the frontend followed by interceptor creation.
- ngnewangFrontend
Then, the Interceptor.
- nggenerateserviceAuthInterceptor
Now go to src/app/app.module.ts
Here, HTTP Module is imported for HTTP Calls to obtain global access.
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, open the interceptor service class and then 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 } 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);
})
);
}
}



Join the conversation! Your thoughts help the community grow.