In this tutorial, we will learn how to build a MEAN stack (MongoDB + Node.js Express + Angular 14) Login, Registration, Token Based Authorization example with JWT in HttpOnly Cookies. The back-end server uses Node.js Express with jsonwebtoken for JWT Authentication & Authorization, Mongoose for interacting with MongoDB database. The front-end will be created with Angular 14 using HttpInterceptor and Router. We’ll also perform Form validation on UI.
Related Post: MEAN Stack CRUD example with Angular 14
Run both projects in one place:
How to Integrate Angular with Node.js Restful Services
Other versions:
– MEAN stack: Login & Registration with Angular 8 example
– MEAN stack: Login & Registration with Angular 10 example
– MEAN stack: Login & Registration with Angular 11 example
– MEAN stack: Login & Registration with Angular 12 example
– MEAN stack: Login & Registration with Angular 13 example
– MEAN stack: Login & Registration with Angular 15 example
Contents
MEAN stack Authentication & Authorization example
It will be a full stack, with Angular 14 for front-end and Node.js Express for back-end with MongoDB database. The access is verified by JWT Token in HttpOnly Cookies.
- User can signup new account (registration), login with username & password.
- Role based Authorization (admin, moderator, user)
The images below shows screenshots of our Angular 14 Client App.
– Anyone can access a public page before logging in:
– New user registration:
Signup Successfully:
– Signup form validation:
If you want to know more details about Form Validation, please visit:
Angular 14 Form Validation example (Reactive Forms)
– Login with legal account:
Login Successfully:
HttpOnly Cookie set by the Server:
– Profile page (for successful Login:
– For Authorization (Moderator account login), the navigation bar will change by authorities:
HttpOnly Cookie sent automatically with HTTP Request:
– Browser Local/Session Storage for storing user information:
– If a User who doesn’t have Admin role tries to access Admin Board page:
– roles collection:
– users collection:
Flow for User Authentication and Authorization
The diagram shows flow for User Registration, User Login and Resource access process.
It’s not too difficult to understand. We have 3 endpoints for authentication:
api/auth/signup
for User Registrationapi/auth/signin
for User Loginapi/auth/signout
for User Logout
This Angular Client uses JWT in Cookies while sending request to protected resources (Authorization).
Node.js Express for Backend
Overview
Our Node.js Express Application with MongoDB can be summarized in the diagram below:
Via Express routes, HTTP request that matches a route will be checked by CORS Middleware before coming to Security layer.
Security layer includes:
- JWT Authentication Middleware: verify SignUp, verify token
- Authorization Middleware: check User’s roles with record in database
If these middlewares throw any error, a message will be sent as HTTP response.
Controllers interact with MongoDB Database via Mongoose ODM library and send HTTP response (token, user information, data based on roles…) to client.
Technology
- Express 4.17.1
- bcryptjs 2.4.3
- cookie-session 1.4.0
- jsonwebtoken 8.5.1
- mongoose 5.13.13
- MongoDB
Project Structure
This is directory structure for our Node.js Express JWT and MongoDB application:
– config
- configure MongoDB database & Mongoose
- configure Auth Key
– routes
- auth.routes.js: POST signup, signin & signout
- user.routes.js: GET public & protected resources
– middlewares
- verifySignUp.js: check duplicate Username or Email
- authJwt.js: verify Token, check User roles in database
– controllers
- auth.controller.js: handle signup, signin & signout actions
- user.controller.js: return public & protected content
– models for Sequelize Models
- user.model.js
- role.model.js
– server.js: import and initialize necessary modules and routes, listen for connections.
Implementation
You can find step by step to implement this Node.js App in the post (with Github):
Node.js Express JWT Auth example with MongoDB
Or you can use MySQL database instead:
Node.js Express JWT Auth example with MySQL
Before running the backend server, you need to add minor configuration:
/* In server.js */
var corsOptions = {
origin: ["http://localhost:8081"],
credentials: true
}
app.use(cors(corsOptions));
Angular 14 for Frontend
Overview
Our Angular 14 App can be summarized in component diagram below:
Let’s try to understand it right now.
– The App
component is a container using Router
. It gets user user information from Browser Session Storage via storage.service
. Then the navbar now can display based on the user login state & roles.
– Login
& Register
components have form for submission data (with support of Form Validation). They use storage.service
for checking state and auth.service
for sending signin/signup requests.
– auth.service
uses Angular HttpClient ($http
service) to make authentication requests.
– every HTTP request by $http
service will be inspected and transformed before being sent by auth-interceptor
.
– Home
component is public for all visitor.
– Profile
component get user
data from Session Storage.
– BoardUser
, BoardModerator
, BoardAdmin
components will be displayed depending on roles
from Session Storage. In these components, we use user.service
to get protected resources from API (with JWT in HttpOnly Cookie).
Technology
- Angular 14
- RxJS 7
- Angular CLI 14
Project Structure
This is the folder structure of our Angular front-end project:
You can understand it properly without any explanation because we’ve looked at the overview before.
Implementation
You can find step by step to implement this Angular 14 Client in the post:
Angular 14 JWT Authentication & Authorization example
Further Reading
- https://mongoosejs.com/
- https://www.npmjs.com/package/jsonwebtoken
- Angular HttpInterceptor
- In-depth Introduction to JWT-JSON Web Token
Fullstack CRUD Application:
Angular 14 + MongoDB + Node Express: CRUD example
Source code
You can find complete source code for this tutorial at Github.
Conclusion
Now we have an overview of MEAN Stack Auth: Node.js Express + Angular 14 + MongoDB Authentication and Authorization example using JWT, HttpInterceptor, Router, Form Validation along with flow for registration and login actions.
We also take a look at Node.js Express server architecture for JWT Authentication using jsonwebtoken & Sequelize, as well as Angular project structure for building a front-end app working with JWT.
Next tutorials will show you more details about how to implement this interesting system:
– Part 2: Node.js Express Back-end
– Part 3: Angular 14 Front-end
You will want to know how to run both projects in one place:
How to Integrate Angular with Node.js Restful Services
Happy learning, see you again!