visit
ng new angFrontend
ng generate service AuthInterceptor
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 { }
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
npm i -S express cors body-parser express-jwt jsonwebtoken
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);
});
//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});
});
node app.js
Listening to 3000
app.get('/path1', (req, res) => {
res.status(200)
.json({
"success": true,
"msg": "Secrect Access Granted"
});
});
//ALLOW PATHS WITHOUT TOKEN AUTHENTICATION
app.use(expressJWT({ secret: secret})
.unless(
{ path: [
'/token/sign'
]}
));
app.get('/path1', (req, res) => {
res.status(200)
.json({
"success": true,
"msg": "Secret Access Granted"
});
});
ng generate component home
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);
}
);
}
Github Repo
Previously published at