Authentication VS Authorisation Using JWT Token

Garv Singh Tomar
9 min readMay 9, 2024

Authentication and authorization are two fundamental pillars of web application security. It helps in ensuring that users are who they claim to be and that they have appropriate access to resources. Authentication verifies the identity of users or clients, while authorization controls access to specific resources or functionalities based on their identity and permissions.

In modern web development, JSON Web Tokens (JWT) have emerged as a popular mechanism for providing secure authentication and authorization processes. It’s a compact, URL-safe token format that securely encodes claims as JSON objects, providing a means for transmitting information between parties in a compact and tamper-evident format. It serves as portable tokens that can be easily verified by web servers to ensure the authenticity of users and grant access to authorized resources/functionalities.

What is Authentication?

Authentication is the crucial process of any web application that verifies the identity of users attempting to access protected resources. It plays a critical role in web security by ensuring that only authorized users gain access to sensitive information. Confirming the authenticity of users helps in preventing unauthorized access and protects data from misuse or manipulation.

Various authentication methods are used in web development to authenticate and validate users identities:

Password-Based Authentication:

  • This traditional method involves users providing their credentials, typically a username and password, to gain access to a system.
  • The system then compares the provided credentials with those stored in the database. If they match, access is granted; otherwise, access is denied.

Token-Based Authentication:

  • Token-based authentication involves issuing a unique token to users upon successful authentication.
  • Instead of repeatedly sending credentials with each request, users include the token in subsequent requests to prove their identity.
  • Tokens can be generated using various techniques, such as JSON Web Tokens (JWT), which securely encode user information and are commonly used in stateless authentication systems.

Examples of authentication mechanisms include:

Session-Based Authentication:

  • In session-based authentication, a session ID is generated and associated with each user upon successful login.
  • The session ID is then stored on the server, generally in memory or database, and sent to the client as a cookie.
  • Subsequent requests from the client include the session ID, allowing the server to retrieve the user’s session data and authenticate them without requiring re-authentication for each request.

Token-Based Authentication:

  • Token-based authentication relies on the exchange of tokens between the client and server to authenticate users.
  • Upon successful authentication, the server generates a token containing relevant user information and signs it using a secret key.
  • The token is then sent to the client, which includes it in subsequent requests to access protected resources.
  • The server validates the token’s authenticity and extracts the user’s identity and permissions from its payload, allowing for seamless and stateless authentication.

What is Authorisation?

Authorization is the process of determining what actions or resources a user is allowed to access within an application. It plays a crucial role in controlling access to sensitive data, functionalities, or resources based on the user’s identity and permissions. By enforcing access control policies, authorization mechanisms prevent unauthorized users from accessing sensitive data or functionalities, thereby maintaining data confidentiality, integrity, and privacy.

Different authorization models are utilized in web development:

1. Role-Based Access Control (RBAC):

  • RBAC assigns permissions to users based on their roles within a system.
  • Users are assigned to specific roles, and each role is granted certain permissions.
  • Access decisions are made based on the roles associated with the user, which streamlines tasks and minimizes complexity.

2. Attribute-Based Access Control (ABAC):

  • ABAC evaluates access decisions based on various attributes or characteristics of users, resources, and the environment.
  • Policies define rules that consider attributes such as user roles, attributes, time of access, and resource properties to determine access rights.
  • ABAC offers fine-grained access control and flexibility in defining access policies based on dynamic conditions.

Examples of authorization mechanisms commonly employed in web development include:

1. Access Control Lists (ACLs):

  • ACLs specify the permissions granted to individual users or groups on specific resources.
  • Each resource maintains a list of users or groups with their associated permissions, allowing for granular control over access rights.
  • ACLs are often used in file systems, databases, or network services to regulate access to resources.

2. Role-Based Access Control (RBAC):

  • RBAC assigns users to roles based on their job responsibilities or organizational roles.
  • Permissions are associated with roles, and users inherit the permissions of the roles they are assigned.
  • RBAC simplifies access management by grouping users with similar access requirements and streamlining permission assignments.

What is a JWT Token?

JSON Web Token (JWT) is a compact and self-contained token format used for securely transmitting information between parties as a JSON object. It serves to securely represent claims between two parties and is commonly used in web authentication and authorization processes.

The structure of a JWT token consists of three parts: header, payload, and signature.

For eg: This is a fully generated JWT token.

  1. Header:
  • The header typically consists of two parts: the token type (“typ”) and the hashing algorithm (“alg”) used to create the signature.
  • The header is base64url-encoded and placed at the beginning of the JWT token.
  • In the example above, the header is ‘ eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9‘, which is base64url-encoded and decodes to {“alg”: “HS256”, “typ”: “JWT”}.

2. Payload:

  • The payload contains the claims or assertions about the user and additional metadata.
  • Claims can be categorized into three types: reserved claims (defined by the JWT specification), public claims (defined by users), and private claims (custom claims agreed upon by parties involved).
  • The payload is also base64url-encoded and follows the header in the JWT token.
  • In the example above, the payload is eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkdhcnYgU2luZ2ggVG9tYXIifQ, which is base64url-encoded and decodes to {“sub”: “1234567890”, “name”: “Garv Singh Tomar”}.

3. Signature:

  • The signature is generated by encoding the header, payload, and a secret key using the specified hashing algorithm.
  • The signature ensures the integrity and authenticity of the JWT token, allowing parties to verify its validity.
  • In the example above, the signature is 2iQd6yIzng61b-WI92I1EMlPvTfFn4WZ8CQksAbVJxE.

JWT tokens are generated, signed, and verified using the following process:

  1. Generation:
  • Upon successful authentication, a JWT token is generated by encoding the header and payload as JSON objects and signing them using a secret key.
  • The resulting JWT token is sent to the client, who includes it in subsequent requests to access protected resources.

2. Signing:

  • The signature is created by concatenating the base64url-encoded header and payload, along with the secret key, and applying the specified hashing algorithm.
  • The resulting signature is appended to the JWT token, creating a complete and tamper-evident token.

3. Verification:

  • To verify the authenticity of a JWT token, the server decodes the header and payload and recalculates the signature using the same secret key and hashing algorithm.
  • If the recalculated signature matches the signature included in the JWT token, the token is considered valid; otherwise, it is rejected.

Considerations for securely handling JWT tokens in web applications include:

  1. Token Expiration:
  • JWT tokens should have a limited lifespan and include an expiration timestamp to mitigate the risk of token misuse or replay attacks.
  • Token expiration helps enforce session management and reduces the window of opportunity for unauthorized access.

2. Token Validation:

  • When validating JWT tokens, ensure that the signature is verified using a secure hashing algorithm and a strong secret key.
  • Validate token claims to enforce access control policies and prevent unauthorized access to resources.

3. Token Revocation:

  • Implement mechanisms for token revocation or blacklisting to invalidate JWT tokens in case of security incidents or user logout events.
  • Consider using token revocation lists (TRLs) or token introspection endpoints to manage token validity.

General Steps for Implementing JWT Authorization in Your Application :

Implementing JWT authorization in your application involves several key steps to ensure secure communication between the client and server:

  1. Set up a server-side application: Begin by creating a backend application that will handle the generation and verification of JWTs. You can use any server-side language and framework, such as Node.js with Express.
  2. Install the necessary packages: Install a JWT library for your chosen server-side language. For instance, if you’re using Node.js, you can install the jsonwebtoken( npm module) library, which provides utilities for working with JWTs, and import it into your code

3. Implement authentication: Your server-side application needs to implement authentication to verify the user’s credentials. This can involve various methods such as email/password authentication or social media authentication.

4. Generate the JWT: After successful authentication, your server-side application generates a JWT containing information about the user, such as their ID, name, and roles. The JWT is signed using a secret key or a public/private key pair to ensure its integrity.

5. Send the JWT to the client: The server sends the generated JWT to the client, typically in response to a successful authentication request. The client then stores the JWT securely, usually in local storage or a secure HTTP cookie, for future use.

6. Send the JWT with every request: Whenever the client wants to access a protected resource on the server, it includes the JWT in the Authorization header of the HTTP request. This allows the server to identify and authenticate the user.

7. Verify the JWT on the server: Upon receiving a request with a JWT, the server verifies the token’s signature using the secret key. If the signature is valid, the server extracts the information contained in the JWT to determine the user’s identity and permissions.

8. Authorize the request: Based on the information extracted from the JWT, the server determines whether the user is authorized to access the requested resource. If authorized, the server fulfills the request and returns the requested data. Otherwise, it returns an error message indicating insufficient permissions.

Following these steps, you can effectively implement JWT authorization in your application, enhancing security and ensuring that only authorized users can access protected resources.

Advantages of using JWT Token:

JWT (JSON Web Token) offers several advantages over other methods for authentication and authorization:

  • Stateless: JWTs don’t require the server to maintain a session state, making them ideal for microservices architectures and horizontally scaling applications. Each request carries all the necessary information for verification.
  • Security: JWTs are digitally signed, ensuring authenticity and preventing tampering by attackers. The signature allows the server to verify the token’s origin and data integrity.
  • Efficiency: Verifying JWTs is faster than traditional session-based authentication because it doesn’t involve database lookups. This gives quicker response times.

Conclusion

In conclusion, we have explored the fundamental concepts of authentication, authorization, and utilization of JWT tokens in web security. Here’s a recap of the key points discussed in this blog:

  • Authentication verifies the identity of users, while authorization controls access to resources based on their identity and permissions. Both processes are essential components of web security, working together to ensure secure access to sensitive data and functionalities.
  • JWT tokens are powerful tools for facilitating authentication and authorization in web applications. With their compact and self-contained format, JWT tokens enable stateless authentication, seamless communication between distributed systems, and fine-grained access control based on customizable claims.

Here’s the GitHub link to implement Authentication and Authorisation using JWT Tokens : Github Link

--

--