Skip to main content

BezKoder

  • Courses
  • Full Stack
  • Spring
  • Node
  • Vue
  • Angular
  • React
  • Firebase
  • Django
  • Dart
  • JsonFormatter
  • Categories

MEAN stack Authentication & Authorization with Angular 13

Last modified: December 24, 2022 bezkoder Angular, Full Stack, MongoDB, Node.js, Security

In this tutorial, we will learn how to build a MEAN stack (MongoDB + Node.js Express + Angular 13) 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 13 using HttpInterceptor and Router. We’ll also perform Form validation on UI.

Related Post: MEAN Stack CRUD example with Angular 13

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 14 example
– MEAN stack: Login & Registration with Angular 15 example


Contents

  • MEAN stack Authentication & Authorization example
  • Flow for User Authentication and Authorization
  • Node.js Express for Backend
    • Overview
    • Technology
    • Project Structure
    • Implementation
  • Angular 13 for Frontend
    • Overview
    • Technology
    • Project Structure
    • Implementation
  • Further Reading
  • Source code
  • Conclusion

MEAN stack Authentication & Authorization example

It will be a full stack, with Angular 13 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 13 Client App.

– Anyone can access a public page before logging in:

mean-stack-authentication-angular-13-example-public-access

– New user registration:

mean-stack-authentication-angular-13-example-registration

Signup Successfully:

mean-stack-authentication-angular-13-example-registration-success

– Signup form validation:

mean-stack-authentication-angular-13-example-form-validation

If you want to know more details about Form Validation, please visit:
Angular 13 Template Driven Forms Validation example

– Login with legal account:

mean-stack-authentication-angular-13-example-login-page

Login Successfully:

mean-stack-authentication-angular-13-example-login-success

HttpOnly Cookie set by the Server:

mean-stack-authentication-angular-13-example-cookie-signin

– Profile page (for successful Login:

mean-stack-authentication-angular-13-example-profile

– For Authorization (Moderator account login), the navigation bar will change by authorities:

mean-stack-authentication-authorization-angular-13-example

HttpOnly Cookie sent automatically with HTTP Request:

mean-stack-authentication-authorization-angular-13-httponly-cookie

– Browser Local/Session Storage for storing user information:

mean-stack-authentication-authorization-angular-13-user-info

– If a User who doesn’t have Admin role tries to access Admin Board page:

mean-stack-authentication-angular-13-example-authorization-failed

– roles collection:

mean-stack-authentication-authorization-roles-collection

– users collection:

mean-stack-authentication-authorization-users-collection

Flow for User Authentication and Authorization

The diagram shows flow for User Registration, User Login and Resource access process.

mean-stack-authentication-authorization-flow

It’s not too difficult to understand. We have 3 endpoints for authentication:

  • api/auth/signup for User Registration
  • api/auth/signin for User Login
  • api/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:

mean-stack-authentication-authorization-server-architecture

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:

mean-stack-authentication-authorization-server-project-structure

– 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 13 for Frontend

Overview

Our Angular 13 App can be summarized in component diagram below:

mean-stack-authentication-authorization-frontend

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 13
  • RxJS 7
  • Angular CLI 13

Project Structure

This is the folder structure of our Angular front-end project:

mean-stack-authentication-authorization-frontend-project-structure

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 13 Client in the post:
Angular 13 JWT Authentication & Authorization with HttpOnly Cookie

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 + Node Express + MongoDB example

Source code

You can find complete source code for this tutorial at Github.

Conclusion

Now we have an overview of Node.js Express + Angular 13 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 13 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!

angular angular 13 authentication authorization express httpinterceptor httponly cookie jwt login mean stack mongodb mongoose node.js security token based authentication

Post navigation

JPA EntityManager example in Spring Boot
JPA/Hibernate One To Many Unidirectional example Spring Boot

Follow us

  • Facebook
  • Youtube
  • Github

Tools

  • Json Formatter
  • .
  • Privacy Policy
  • Contact
  • About
DMCA.com Protection Status © 2019-2022 bezkoder.com
X