JSON  Web  Tokens  (JWT)

JSON Web Tokens (JWT)

JSON Web Tokens (JWT) are a standard for representing claims securely between two parties. JWTs can be used to transmit information between parties in a compact and self-contained manner. There are two types of tokens commonly used in authentication systems: access tokens and refresh tokens.

In this blog post, we'll explore the history of JWT, how to install and use it, and dive into the concepts of access tokens and refresh tokens.

⭐History of JSON Web Tokens (JWT):

JSON Web Tokens were introduced as an open standard (RFC 7519) in 2015. They provide a compact, URL-safe means of representing claims to be transferred between two parties. JWTs are commonly used for authentication and authorization purposes in web development. The flexibility and simplicity of JWTs make them suitable for various scenarios, from user authentication to information exchange between services.

⭐Installation:

To use JWT in a Node.js application, you can install the jsonwebtoken library using npm or yarn. Open your terminal and run one of the following commands:

# Using npm
npm install jsonwebtoken

# Using yarn
yarn add jsonwebtoken

Once the library is installed, you can use it in your Node.js application to create and verify JWTs.

⭐ Access Token:

  • An access token is a short-lived token that is used to access protected resources on behalf of a user.

  • It is issued by the authentication server after the user successfully authenticates and authorizes the client application.

  • Access tokens typically have a relatively short expiration time, and they are included in the headers of HTTP requests to protected resources.

  • The receiving server can then validate the access token to ensure that the client has the necessary permissions to access the requested resource.

Let's create a simple example of how to generate an access token using JWT in a Node.js application. Consider the following code snippet:

userSchema.methods.generateAccessToken = function(){
    return jwt.sign(
        {
            _id: this._id,
            email: this.email,
            username: this.username,
            fullName: this.fullName
        },
        process.env.ACCESS_TOKEN_SECRET,
        {
            expiresIn: process.env.ACCESS_TOKEN_EXPIRY
        }
    )
}

In this example:

  • We use the jsonwebtoken library to sign a payload containing user information.

  • The payload typically includes user-specific claims such as _id, email, fullname and username.

  • The signing process involves a secret key (ACCESS_TOKEN_SECRET) and an optional expiration time (ACCESS_TOKEN_EXPIRY)

Refresh Token:

  • A refresh token is a long-lived token used to obtain a new access token.

  • Unlike access tokens, refresh tokens are not meant to be sent with each request to access a protected resource.

  • Instead, when an access token expires, the client can use the refresh token to request a new access token from the authentication server.

  • Refresh tokens are typically kept secure on the client side and are not transmitted over the network frequently, reducing the risk associated with interception.

Similarly, we can generate a refresh token using a method like the one below:

userSchema.methods.generateRefreshToken = function(){
    return jwt.sign(
        {
            _id: this._id,
        },
        process.env.REFRESH_TOKEN_SECRET,
        {
            expiresIn: process.env.REFRESH_TOKEN_EXPIRY
        }
    )
}

The refresh token typically contains fewer claims and has a longer expiration time compared to the access token. It is used to obtain a new access token when the original one expires.

⭐Conclusion:

JSON Web Tokens have become a crucial tool in web development for secure information exchange. They offer a standardized way to authenticate and authorize users while maintaining simplicity and flexibility. With libraries like jsonwebtoken readily available, integrating JWT into your Node.js applications is a straightforward process. Understanding the distinction between access tokens and refresh tokens is essential for building secure and efficient authentication systems.