1570179099
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 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.
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.
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, 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);
})
);
}
}
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.
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.
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:Json-Web-Token-Authentication-with-Angular-8-and-Node-JS
#web-development #angular #node-js #json
1622798007
In this tutorial, I will show you how to build a full stack Angular 12 + Spring Boot JWT Authentication example. The back-end server uses Spring Boot with Spring Security for JWT Authentication & Role based Authorization, Spring Data JPA for interacting with database. The front-end will be built using Angular 12 with HttpInterceptor & Form validation.
Related Posts:
– Angular 12 + Spring Boot: CRUD example
– Angular 12 + Spring Boot: File upload example
– Spring Boot, MongoDB: JWT Authentication with Spring Security
Contents [hide]
#angular #full stack #spring #angular #angular 12 #authentication #authorization #jwt #login #registration #security #spring boot #spring security #token based authentication
1602036957
Laravel 8 rest api authentication with passport tutorial, you will learn step by step how to create rest API with laravel 8 passport authentication. And as well as how to install and cofigure passport auth in laravel 8 app.
Step 1: Download Laravel 8 App
Step 2: Database Configuration
Step 3: Install Passport Auth
Step 4: Passport Configuration
Step 5: Run Migration
Step 6: Create APIs Route
Step 7: Create Passport Auth Controller
Step 8: Now Test Laravel REST API in Postman
https://www.tutsmake.com/laravel-8-rest-api-authentication-with-passport/
#laravel api authentication with passport #laravel 8 api authentication #laravel 8 api authentication token tutorial #laravel 8 api authentication using passport #laravel 8 api authentication session
https://loizenai.com Programming Tutorial
1603027896
https://loizenai.com/angular-10-nodejs-jwt-authentication-mysql-examples-tutorials/
“How to implement Angular 10 + Nodejs JWT Token Based Authentication with MySQL Example?” is always a big common question in development world? So in the tutorial, I guide you very clearly how to build a full stack example to demonstrate an JWT Authentication flow from Angular (signup & signin with by JWT Token) to backend: Nodejs and database MySQL.
YOUTUTBE: https://youtu.be/rYmf_MthobU
Link post: https://loizenai.com/angular-10-nodejs-jwt-authentication-mysql-examples-tutorials/
#angular #jwt #nodejs #mysql #authentication
https://loizenai.com Programming Tutorial
1601744764
“How to implement Angular 10 + Nodejs JWT Token Based Authentication with MySQL Example?” is always a big common question in development world? So in the tutorial, I guide you very clearly how to build a full stack example to demonstrate an JWT Authentication flow from Angular (signup & signin with by JWT Token) to backend: Nodejs and database MySQL.
JSON Web Token (JWT) defines a compact and self-contained way for securely transmitting information between parties as a JSON object.
Scenarios where JSON Web Tokens are useful:
Authorization: the most common scenario for using JWT. Single Sign On is a feature that widely uses JWT
Information Exchange: Because JWTs can be signed, JSON Web Tokens are a good way of securely transmitting information between parties.
JSON Web Tokens consist of 3 parts:
Header
Payload
Signature
-> JWT looks like Header-Base64-String.Payload-Base64-String.Signature-Base64-String
Header consists of two parts:
token type.
hashing algorithm.
We will build an application, from frontend (Angular) to backend (Nodejs/Express), which allows users to register, login account. This application is secured with JWT (JSON Web Token) authentication and Nodejs middleware security. Then, depending on the role of current User (user, pm or admin), this system accepts what he can access
HTTP request that matches route will be accepted by CORS Middleware before coming to Security layer.
Security layer includes:
– JWT Authentication Middleware: verify SignUp, verify token
– Authorization Middleware: check User’s roles
Main Business Logic Processing interacts with database via Sequelize and send HTTP response (token, user information, data based on roles…) to client.
– app.component is the parent component that contains routerLink and router-outlet for routing. It also has an authority variable as the condition for displaying items on navigation bar.
– user.component, pm.component, admin.component correspond to Angular Components for User Board, PM Board, Admin Board. Each Board uses user.service to access authority data.
– register.component contains User Registration form, submission of the form will call auth.service.
– login.component contains User Login form, submission of the form will call auth.service and token-storage.service.
– user.service gets access to authority data from Server using Angular HttpClient ($http service).
– auth.service handles authentication and signup actions with Server using Angular HttpClient ($http service).
– every HTTP request by $http service will be inspected and transformed before being sent to the Server by auth-interceptor (implements HttpInterceptor).
– auth-interceptor check and get Token from token-storage.service to add the Token to HTTP Request Header.
– token-storage.service manages Token inside Browser’s sessionStorage.
Link Tutorial: https://loizenai.com/angular-10-nodejs-jwt-authentication-mysql-examples-tutorials/
Youtube Link: https://youtu.be/rYmf_MthobU
GitHub: https://github.com/loizenai/Nodejs-Tutorials/tree/master/Angular 10 Nodejs JWT Token Based Authentication Example - Backend-Sourcecode
#nodejs #angular #angular10 #jwt #authentication #mysql
https://loizenai.com Programming Tutorial
1602250418
https://loizenai.com/angular-10-nodejs-jwt-authentication-mysql-examples-tutorials/
“How to implement Angular 10 + Nodejs JWT Token Based Authentication with MySQL Example?” is always a big common question in development world? So in the tutorial, I guide you very clearly how to build a full stack example to demonstrate an JWT Authentication flow from Angular (signup & signin with by JWT Token) to backend: Nodejs and database MySQL.
Tutorial Link: https://loizenai.com/angular-10-nodejs-jwt-authentication-mysql-examples-tutorials/
#angular #nodejs #authentication #jwt #mysql #express