Authentication and Authorization in Express

Learn via video courses
Topics Covered

Overview

One of the crucial components of every web application is user authentication and permission. There are many different ways to manage authentication, and we can rely on services provided by outside parties like Passport. But in this essay, we'll choose a very straightforward and independently devised approach that will help us comprehend the essence of authentication.

Introduction

In the context of web development, authentication and authorization in express are important concepts that play a crucial role in `securing applications and controlling access to resources. Let's explore each concept individually:

Authentication:

Authentication is the process of verifying the identity of a user or entity. It ensures that the user claiming to be a particular person or entity is indeed who they say they are. In web applications, authentication is typically performed when a user tries to access protected resources or perform privileged actions.

There are several commonly used authentication mechanisms:

  • Username and password: This is the most common method where users provide a username (or email) and a password to prove their identity.
  • Token-based authentication: Tokens, such as JSON Web Tokens (JWT), are generated and issued to users upon successful authentication. These tokens are then included in subsequent requests to authenticate and authorize the user.
  • Single sign-on (SSO): SSO allows users to authenticate once and gain access to multiple applications or services without providing their credentials repeatedly.

The authentication process usually involves the following steps:

  • The user provides their credentials.
  • The server verifies the provided credentials.
  • If the credentials are valid, the server generates an authentication token or session for the user.
  • The token/session is sent back to the client and stored for subsequent requests.
  • The client includes the token/session in each request to prove its authenticity.

Authorization:

Authorization determines the actions or resources a user is allowed to access within an application after successful authentication. Once a user's identity is established, the authorization process enforces access control rules and permissions to ensure that the user can only perform their authorized actions.

Authorization is typically based on roles, permissions, or policies assigned to users. Some common authorization mechanisms include:

  • Role-based access control (RBAC): Users are assigned specific roles (e.g., admin, moderator, user), and each role has a set of predefined permissions that determine what actions or resources they can access.
  • Attribute-based access control (ABAC): Access control decisions are made based on various attributes associated with users, resources, and environmental conditions.
  • Policy-based access control: Access control policies are defined in a centralized manner, specifying the conditions and rules for granting or denying access to resources.

The authorization process generally involves the following steps:

  • The server receives a request from an authenticated user.
  • The server identifies the user and retrieves their assigned roles or permissions.
  • The server evaluates the requested action or resource against the user's roles or permissions.
  • If the user is authorized, the server allows the action or provides access to the requested resource; otherwise, it denies access and returns an appropriate response.

Using various middleware libraries and techniques, you can implement authentication and authorization in Express. These libraries help you handle user authentication, generate and verify tokens, manage sessions, and enforce access control rules based on user roles or permissions. By properly implementing authentication and authorization in the express application, you can protect sensitive data, control user access, and ensure the security of your application and its resources.

What is Authentication & Authorization?

In plain English, authentication is the process of confirming a user's identity (i.e., who you are), and authorization is the process of confirming their access to information (i.e., what you are permitted to do).

Administrators employ authentication and authorization in expression as two crucial information security processes to safeguard systems and data. A user's or service's identity is confirmed through authentication, and their access privileges are established through authorization. Although the two phrases have a similar sound, they serve different but just as important functions in protecting applications and data. It's essential to comprehend the differences. They determine a system's security when taken together. Without adequately configured authentication and authorization in express, a solution cannot be considered secure.

Authentication: What is it?

Authentication is the process of confirming that a person or thing is who they claim to be. To safeguard access to a program or its data, technology systems normally require some type of authentication. For instance, you often need to enter your login and password to access a website or service online. Then, in the background, it checks your entered username and password to a record in its database. The system assumes you are a legitimate user and provides you access if the data you provided matches. In this illustration, system authentication assumes that only you would be aware of the proper login and password.

What is Authorization

The security procedure known as authorization establishes a user's or service's level of access. In technology, authorization is used to grant users or services permission to access certain data or carry out specific tasks. If we go back to our coffee shop example, we see that Rahul and Lucia play different roles there. Rahul is only allowed to place and view orders because he is a barista. On the other side, Lucia might also have access to the daily sales totals in her capacity as manager. Rahul and Lucia work in separate capacities at the coffee shop, therefore the system would use their verified identities to grant each user certain access. It is crucial to understand the distinction between authentication and authorization in this context.

Difference between Authorization and Authentication

Authentication and authorization in express are two distinct concepts that serve different purposes in securing and controlling access to resources within a web application. Let's explore the differences between authentication and authorization in express:

In Express.js, authentication typically involves validating user credentials, such as a username and password, and generating a session or authentication token upon successful verification. The authentication process can use various strategies and middleware, such as Passport.js, to handle authentication mechanisms like username/password, social logins, or token-based authentication. The result of successful authentication is typically a user session or an authentication token, which is used to identify the authenticated user in subsequent requests. The authenticated user's identity can be stored in the session object or encoded within the authentication token.

In Express.js, authorization is typically implemented using middleware functions that examine the authenticated user's credentials, roles, or permissions and determine if they have the necessary authorization to perform a specific action or access a particular resource. This middleware can be custom-built or leveraged from third-party libraries, such as express-jwt for token-based authorization.

Authorization can be based on various models, such as role-based access control (RBAC), where users are assigned roles with specific permissions, or attribute-based access control (ABAC), where access decisions are made based on attributes associated with users, resources, or environmental conditions. By implementing authorization in Express.js, you can enforce access control rules and ensure that only authorized users can perform certain actions or access sensitive resources. This helps protect the application's data and functionality from unauthorized access and maintains the overall security of the system.

Similarity between authentication & authorization

While authentication and authorization are distinct concepts with different purposes in Express.js, they share some similarities. Here are a few similarities between authentication and authorization in Express.js:

  • User Identification: Expressjs authentication and authorization involve identifying the user or entity accessing the application. In both processes, the user's identity is established, typically through the authentication process, before authorization checks are performed.
  • Middleware: Authentication and authorization in Express.js are often implemented using middleware functions. Middleware functions are intermediaries that intercept incoming requests and perform specific tasks, such as verifying authentication credentials or checking authorization permissions. They are integrated into the application's request handling pipeline and provide a modular and reusable approach to handle Expressjs authentication and authorization logic.
  • User Context: Expressjs authentication and authorization provide a context within the application for the authenticated user. Once a user is successfully authenticated, their identity is typically stored in a session object or encoded within an authentication token. This context is then used in subsequent requests to determine the user's authorization privileges and access rights.
  • Security Enhancement: Both authentication and authorization contribute to enhancing the security of an Express.js application. Authentication ensures that only valid users with verified identities can access the application, while authorization restricts access to specific resources or actions based on the user's assigned permissions. By implementing both authentication and authorization, developers can mitigate the risk of unauthorized access, protect sensitive data, and enforce proper access control.
  • Middleware Ordering: In Expressjs authentication and authorization middleware can be ordered and applied selectively based on the application's requirements. Middleware functions can be applied globally to all routes or selectively to specific routes or groups of routes. This flexibility allows developers to apply authentication and authorization checks where necessary, customizing the behavior based on the desired access control policies.

While authentication and authorization serve distinct purposes, they often work together to provide a comprehensive security framework within an Express.js application. Authentication establishes trust and verifies user identities, while authorization controls access and determines what actions or resources a user is allowed to access based on their authenticated identity and assigned permissions.

Why use Authentication & Authorization?

Purpose of using Authorization:

The purpose of the authorization is to enforce access control and determine what actions or resources an authenticated user or entity is allowed to access within a system or application. Authorization plays a crucial role in ensuring the security, integrity, and confidentiality of sensitive information by restricting access to authorized individuals or entities.

Here are some key purposes and benefits of authorization:

  • Security: Authorization helps protect sensitive data and resources by allowing only authorized users to access them. By defining and enforcing access control policies, organizations can ensure that confidential information remains secure and is only accessible to those with proper permissions.
  • Privacy: Authorization allows organizations to control access to personal or private information. By specifying who can view, modify, or delete certain data, organizations can safeguard the privacy of `individuals and comply with data protection regulations.
  • Data Integrity: Authorization helps maintain the integrity of data by ensuring that only authorized users can modify or delete information. By enforcing proper access controls, organizations can prevent unauthorized or malicious changes to critical data, preserving its accuracy and reliability.
  • Compliance: Authorization plays a crucial role in meeting regulatory and compliance requirements. Many industries have specific regulations that mandate access control and the protection of sensitive data. By implementing proper authorization mechanisms, organizations can demonstrate compliance and mitigate the risk of legal or regulatory penalties.
  • Least Privilege Principle: Authorization follows the principle of least privilege, which states that users should only have the minimum privileges necessary to perform their tasks. By granting specific permissions based on roles or attributes, organizations can limit potential damage caused by insider threats, accidental misuse, or unauthorized access.
  • User Management: Authorization facilitates user management by allowing administrators to define and manage user roles, permissions, and access levels. This simplifies the process of granting or revoking access to resources as user roles or responsibilities change over time.
  • Auditing and Accountability: Authorization mechanisms often provide logging and auditing capabilities, allowing organizations to track and monitor user actions. This helps in identifying any unauthorized access attempts, detecting suspicious activities, and providing an audit trail for investigations or compliance purposes.

Overall, the purpose of the authorization is to control and manage access to resources, ensuring that only authorized users can perform specific actions or access sensitive information. By implementing robust authorization mechanisms, organizations can protect their data, maintain compliance, and mitigate security risks.

Purpose of using Authentication:

Authentication is an essential aspect of web application development to ensure that only authorized users can access certain resources or perform specific actions. In the context of Express.js, which is a popular web framework for Node.js, authentication is crucial for protecting routes, handling user sessions, and maintaining security. The primary purposes of user authentication in Express.js are:

  • User Identification: Authentication allows the identification of individual users accessing the web application. It verifies the user's identity by validating their credentials, such as a username and password combination or a token.
  • Access Control: Authentication helps in enforcing access control by determining what resources or routes a user is allowed to access based on their authenticated status and user roles or permissions. It prevents unauthorized users from accessing sensitive information or performing restricted actions.
  • User Sessions: Authentication mechanisms in Express.js typically involve the creation and management of user sessions. When a user logs in successfully, a session is established, and a unique session identifier (usually stored as a cookie) is associated with that user. Subsequent requests from the same user include the session identifier, allowing the server to maintain the session state and provide personalized experiences.
  • Protecting Routes: With authentication, you can secure specific routes or endpoints within your Express.js application. Certain routes may require authentication to be accessed, while others can be publicly available. By enforcing authentication on protected routes, you ensure that only authenticated users can access or modify sensitive data or perform critical operations.
  • User Management: Authentication is also crucial for user management functionalities, such as registration, password resets, and user profile updates. By verifying the user's identity, you can securely handle these operations and ensure that only the authenticated user can modify their information.
  • Security: Authentication is a vital security measure to protect against unauthorized access, data breaches, and potential attacks like identity theft, session hijacking, or cross-site scripting (XSS). By properly implementing authentication mechanisms, you can enhance the overall security posture of your Express.js application.

Express.js provides various authentication middleware and libraries, such as Passport.js, that make it easier to implement authentication functionalities in your application. These tools offer flexibility in choosing authentication strategies like username/password, JSON Web Tokens (JWT), OAuth, or other third-party authentication providers, depending on your specific requirements.

What is JWT Token

JSON Web Token (JWT) is a compact, URL-safe means of representing claims between two parties. It is a self-contained token that contains JSON-encoded information, allowing for secure transmission of data between parties in a compact and verifiable format. JWTs are commonly used for authentication and authorization purposes in web applications. JWTs consist of three parts: a header, a payload, and a signature, each encoded and separated by dots.

Header:

The header contains information about the type of token (JWT) and the algorithm used to sign it. It is typically encoded using Base64Url encoding.

Payload:

The payload, also known as the claims, contains the actual data being transmitted. It includes information about the user or any other relevant metadata. The payload can contain registered claims (predefined standard claims) or custom claims (specific to the application). Like the header, the payload is also Base64Url encoded.

Signature:

The signature is used to verify the integrity of the token and ensure that it has not been tampered with. The signature is created by combining the encoded header, the encoded payload, and a secret key known only to the server. The resulting string is hashed using a specified algorithm (such as HMACSHA256 or RSA) to produce the signature.

When a JWT is sent to the server, the server can verify its authenticity by checking the signature using the secret key. If the signature is valid, the server can trust the information contained in the token.

JWTs are commonly used in authentication workflows. When a user logs in successfully, the server generates a JWT and sends it back to the client. The client then includes the JWT in subsequent requests, typically in the Authorization header using the "Bearer" scheme. The server can then verify the JWT and extract the necessary information to authenticate and authorize the user.

JWTs have several advantages, including statelessness (as the token carries all necessary information), scalability (as the server doesn't need to store session data), and interoperability (as JWTs can be used across different platforms and languages).

However, it's important to securely handle and store the secret key used for signing JWTs, as a compromised key could lead to unauthorized access. Additionally, JWTs should not contain sensitive information that could be accessed by anyone with the token, as JWTs are not encrypted and can be decoded by anyone who has access to them. Because they can be signed (Information Exchange), JWTs are a good technique for securely transferring information between parties. Although JWT can be used with any kind of communication channel, it is currently quite popular for managing HTTP-based authentication and authorization.

Here is the diagram of how JWT works:

JWT works structure

Structure of a JWT:-

  1. The header, which is a string that has been Base64-encoded, is the initial part of the JWT. It provides the hashing algorithm that was used to produce the token's sign and type. The header would appear something like this if it were decoded:

{ "alg": "HS256", "typ": "JWT"}

  1. The payload, or the second portion, comprises the JSON object with user data, such as (id or id_type), which was returned to the user. This is merely Base64-encoded, so anyone can easily decode it.

{"sub": "1234567890", "name": "John Doe", "userId": "1516239022", "user_type_id":1 }

The token's signature is made in the final part using the procedure stated in the header section.

JWT works structure1

How to apply Authentication?

Administrators should be able to create certain user access privileges, choose whether information can be shared internally with partners and authorities, and manage how long data is retained to protect the data in a security system.

Entering a login and password to access a website is a typical illustration. Providing accurate login information informs the website of your identity.

  1. Who you are?
  2. That you are the one who is using the website.

Two user types (admin & user) will exist. All users must first log in and register, and only administrators and common users are authorized.` Regular users will be able to view regular events, while administrators will be able to access special events.

Suppose there are four routes and REST APIs to get this journey started: 1- POST login route ( everyone has access) 2- POST register route ( everyone has access) 3- GET events array (only regular user has access) 4- GET special events array (only admin user has access)

Step 1

  • Start by creating a blank Node.js project using the default settings in your terminal.
  • The Express framework, JWT, bcryptjs, and mongoose should now be installed:
  • Then Express will be used as the router to establish the fundamental framework for various endpoint types, such as registration and login. Additionally, we'll make a routers folder (routers/index.js).
  • Next, let's create a file named (middleware/auth.js) that will serve as our authentication service and a file called (controllers/user) that will serve as our controller for user functions.
  • Let's now build our server, use these modules, and set them up in the Express app (server.js):

Step 2

  • Go to the routers/index.js folder to set the express Router import userController configuration now.

Step 3:

To add userController functions, navigate to the routers' controllers/user subdirectory now.

  • Connect to DB
  • Register function creation
    • Using the bcrypt module, hash a password
    • Construct a user object.
    • User saving in the database
    • then create the payload Create an access token (for information on payload, see the section on JWT structure).

Note: Let's submit a POST request after the authentication service is operational to check whether or not registration is successful.

To do this, I'll be utilising Postman's rest-client. Use Insomnia or any other rest client of your choosing to complete this.

  • Let's provide the following JSON` to the link endpoint: "email": "d@a.hh", "name": "lotfy", "password": "123456", and "user_type_id": 1"
  • The response that you should receive is the access token: The "Token" is "eyJhbGciOiJIUz..."

jwt works structure3

Step 4:

Now that we have registered a new user, we must log in using their credentials after receiving a token as a response.

  • create a login function
    • make login comparison functions credentials and a hashed password.
    • Construct the payload Create a return token and an access token in headers.

Note: Let's submit a POST request to test whether or not Login is functional.

  • Let's post a request with the following JSON to the link endpoint: "Password": "123456", "email": "d@a.hh".
  • You should receive a 200 code and the following access token in the response's header: "auth-token": "eyJhbGciOiJIUz."

jwt works structure4

How to Apply Authorization?

As we previously indicated, we created a field named "user_type_id" that serves as an identifier for the type of user who is requesting this data in the authentication processes (register/login).

Step 1

We now need to switch to our auth file in (middleware/auth.js) whenever a request for a user who is signed in or if someone tries to hack my APIs.

  • Ensure that the request has an access token.
  • Remove the Bearer character from the request header string.
  • Use my token secretKey to verify the user token.
  • We must now determine the type of logged-in user.

Step 2:

Now that the user has been confirmed, we must determine whether this route is intended for administrators or just regular users by using my authentication middleware to check routes according to user type in the file (routers/index.js).

  • Call the get user events function if these criteria are true.

Note: Send a request to test the special route for the admin user whose user_type_id is equal to 1.

  • Let's submit a post request with the following permission header and TYPE Bearer to the link endpoint. token and token value: eyJhbGciOiJIUz...
  • The success with 200 code and the special events array should be returned as a response:

"_id": "1", "name": "Auto Expo Special", "description": "lorem ipsum", and "date": "2012-04-23T18:25:43.511Z" .....

jwt works structure5

Conclusion

Here's a summary of the key points regarding authentication and authorization in Express.js:

  • Authentication:

    • Authentication is the process of verifying the identity of a user or entity accessing a system or resource.
    • In Express.js, authentication involves validating user credentials, establishing user sessions, or verifying tokens.
    • Authentication ensures that only authorized users can access protected resources or perform specific actions.
    • It helps in user identification, access control, user session management, and securing sensitive routes and resources.
    • Common authentication mechanisms in Express.js include username/password, JSON Web Tokens (JWT), and OAuth.
  • Authorization:

    • Authorization is the process of granting or denying access to specific resources or functionalities based on user roles or permissions.
    • It comes after authentication to determine what an authenticated user can or cannot do within the application.
    • Authorization is typically implemented by associating roles or permissions with users and validating them during the authentication process or within route handlers.
    • It helps protect sensitive data, ensure proper access control, and enforce business rules.
    • Authorization can be implemented through middleware, route handlers, or custom functions to check user roles or permissions before granting access.