DEV Community

Cover image for Node.js + Angular 11: JWT Authentication & Authorization example
bezkoder
bezkoder

Posted on • Updated on • Originally published at bezkoder.com

Node.js + Angular 11: JWT Authentication & Authorization example

In this tutorial, we will learn how to build a full stack Node.js Express + Angular 11 Authentication example. The back-end server uses Node.js Express with jsonwebtoken for JWT Authentication & Authorization, Sequelize for interacting with MySQL database. The front-end will be created with Angular 11, HttpInterceptor and Router. We’ll also perform Form validation on UI.

JWT (JSON Web Token)

Comparing with Session-based Authentication that need to store Session on Cookie, the big advantage of Token-based Authentication is that we store the JSON Web Token (JWT) on Client side: Local Storage for Browser, Keychain for IOS and SharedPreferences for Android… So we don’t need to build another backend project that supports Native Apps or an additional Authentication module for Native App users.

in-depth-introduction-jwt-token-based-authentication

There are three important parts of a JWT: Header, Payload, Signature. Together they are combined to a standard structure: header.payload.signature.

The Client typically attaches JWT in x-access-token header:

x-access-token: [header].[payload].[signature]
Enter fullscreen mode Exit fullscreen mode

For more details, you can visit:
In-depth Introduction to JWT-JSON Web Token

Node.js Express Angular 11 Authentication example

It will be a full stack, with Node.js Express for back-end and Angular 11 for front-end. The access is verified by JWT Authentication.

  • User can signup new account, login with username & password.
  • Authorization by the role of the User (admin, moderator, user)

Screenshots

The images below shows screenshots of our Angular 11 Client App.

– Anyone can access a public page before logging in:

jwt-authentication-node-js-angular-11-login-registration-public-page

– A new User can signup:

jwt-authentication-node-js-angular-11-login-registration-signup-page

– Registration form validation:

jwt-authentication-node-js-angular-11-login-registration-form-validation

– Login with legal account:

jwt-authentication-node-js-angular-11-login-registration-signin-page

Profile page:

jwt-authentication-node-js-angular-11-login-registration-profile-page

– UI for admin role:

jwt-authentication-node-js-angular-11-login-registration-authorization

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

jwt-authentication-node-js-angular-11-login-registration-unauthorized

Demo

This is full Angular + Node.js Express JWT Authentication & Authorization App Demo (with form validation, check signup username/email duplicates, test authorization with 3 roles: Admin, Moderator, User).

In the video, we use Angular 10, but the logic and UI are the same as this Angular version 11.

Flow for User Registration and User Login

The diagram shows flow of User Registration, User Login and Authorization process.

jwt-authentication-node-js-angular-11-login-registration-flow

We have 2 endpoints for authentication:

  • api/auth/signup for User Registration
  • api/auth/signin for User Login A legal JWT must be added to HTTP x-access-token Header if Client accesses protected resources.

Back-end with Node.js Express & Sequelize

Our Node.js Express Application can be summarized in the diagram below:

jwt-authentication-node-js-angular-11-login-registration-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 MySQL Database via Sequelize and send HTTP response (token, user information, data based on roles…) to client.

Front-end with Angular 11, HttpInterceptor and Router

jwt-authentication-node-js-angular-11-login-registration-components

For more details, please visit:
https://bezkoder.com/node-js-angular-11-jwt-authentication/

Further Reading

Fullstack CRUD App:

Using HttpOnly Cookies for JWT: (updated)
Node Express + Angular: Authentication & Authorization example

Top comments (12)

Collapse
 
jdforsythe profile image
Jeremy Forsythe

This is dangerous. The JWT should not be available to the client side code at all, let alone stored in SessionStorage.

The proper way is to set the JWT as a secure, http-only cookie that isn't accessible to the client code. It removes the need for the token storage service and interceptor, because the cookie is sent automatically, and it removes the chance of the token being stolen and someone impersonating your users.

Collapse
 
anduser96 profile image
Andrei Gatej

Apart from XSS attacks, which are less likely to happen IMO if you're careful with the libraries you're using, what would be other downsides to storing the token in LocalStorage?

Also, if you go with the cookie approach, you'll have to make sure that you prevent CSRF attacks from happening.

Collapse
 
tis profile image
Tomasz Struczyński

See my comment, for example session impersonation etc.

Collapse
 
justintime4tea profile image
Justin Gross • Edited

This is another example of a tutorial where it is fine for learning though not for learning how to do auth in production.

Please do not roll you're own auth in production. If you want to prototype something quickly then sure, roll your own auth, otherwise you should be using the defacto auth standard OpenID. Do not implement OpenID yourself there are a ton of providers and several good open source servers.

Do auth right, for your users sake.

Collapse
 
bezkoder profile image
bezkoder

Hi all, I've updated the project with HttpOnly Cookies for storing JWT:
Node Express + Angular: Authentication & Authorization example

Collapse
 
tis profile image
Tomasz Struczyński

Session impersonation, for example. In JWT approach, token is basically your session and can be used until expired. If you make it available to sites code, it becomes a target of any malicious script, browser extension etc. And if developer sets long expiration date, it becomes basically open door to your account if anyone intercepts it.

Collapse
 
anduser96 profile image
Andrei Gatej

Where would that malicious script come from, assuming that the dev has done some research on the libs he/she is using and also that a modern framework is used. I'd say the same caution should be taken in the case of browsers extensions.

The second problem can be mitigated by setting a short expiring date and adding a refresh token, which should last longer.

Collapse
 
tis profile image
Tomasz Struczyński

Supply chain attacks are getting more and more popular. It is not only about your project dependencies, their dependencies dependencies and so on. Even popular libraries can (and are) compromised.

Anyway, among security professionals there is a strong movement to restrict JWT to authentication and not as session tokens.

You may want to look at curity.io/resources/architect/api-... or other articles about JWT (in)security.

Thread Thread
 
anduser96 profile image
Andrei Gatej

Makes sense. Thank you for sharing!

Collapse
 
vdelitz profile image
vdelitz

Man, I just came across your React Authentication articles and that reminded me of a project I was working on 2 years, where your tutorials helped me to implement user authentication properly in React and Node.js. As authentication evolves: have you ever worked with passkeys / WebAuthn. If yes, how do you see it compared to password-based authentication?

Collapse
 
cahedral profile image
cahedral

How can I test this code?

Collapse
 
wegitit profile image
weeee

Well put together piece.
Solid pro & con talk in the comments.