Access Token and Refresh Token

Table of contents

Access Token

In simple terms, an access token is like a digital key that grants you permission to access certain resources or services. It's a security measure commonly used in web APIs and authentication systems to control who can do what.

Here's how it works:

    • Authentication: You provide your credentials (username, password, or other means) to a system to verify your identity.

      • Token Generation: If your credentials are valid, the system generates a unique access token and sends it back to you.

      • Accessing Resources: When you make subsequent requests to protected resources or services, you include the access token in your request headers.

      • Authorization Check: The system validates the token to ensure it's legitimate and hasn't expired.

      • Access Granted: If the token is valid, you're granted access to the requested resource or service.

Key Characteristics:

  • Temporary: Access tokens typically have short lifespans (e.g., minutes or hours) to enhance security.

  • Specific Permissions: They often define the specific actions you're authorized to perform.

  • Encoded Data: They often contain encoded information about your identity, permissions, and expiration time.

Common Use Cases:

  • API Authorization: Access tokens are widely used to control access to web APIs, ensuring only authorized users can interact with sensitive data or functionality.

  • Single Sign-On (SSO): They enable seamless logins across multiple applications without requiring re-entering credentials, creating a smoother user experience.

  • Social Media Integrations: When you connect a third-party app to your social media account, access tokens are used to manage permissions and data sharing.

  • Secure File Sharing: They can protect sensitive files by requiring valid access tokens for download or viewing.

Example Scenario:

Imagine you're using a weather app that needs to access your location data. To get this information:

  1. You sign in to the app, granting it access to your location.

  2. The app receives an access token from your device's operating system.

  3. When the app requests weather data, it includes the access token, proving it has permission to access your location.

  4. The weather service verifies the token and, if valid, provides the weather data for your specific location.

Remember: Access tokens play a crucial role in securing online interactions and protecting sensitive data. By understanding their purpose and usage, you can make informed decisions about how your information is shared and protected in various online services.

Here is an example of generating access tokens through JSON Web Token :

This code will only work if you have already made your *userSchema*

userSchema.methods.accessTokenGenerator = 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,
        },
    );
};

Refresh Token

A refresh token is like a special key tucked away, used to obtain new access tokens when current ones expire. It plays a crucial role in maintaining an uninterrupted and convenient user experience for secure online sessions.

Here's how it works:

  1. Initial Login:

    • You log in to a website or app with your credentials.

      • The server verifies your identity and generates two tokens: Access Token: Provides temporary permission to access resources (short lifespan).

      • Refresh Token: Long-lasting key used to get new access tokens.

  2. Accessing Resources:

    • Your device securely stores the access token.

    • When you interact with the app, the access token is sent with each request for authorization.

  3. Token Expiration:

    • Access tokens have short lifespans (minutes, hours) for enhanced security.

    • Upon expiry, the app attempts to use the refresh token to get a new access token silently.

  4. Refresh Token Exchange:

    • The app sends the refresh token to the server for verification.

    • If valid, the server generates a new access token and sends it back to the app.

  5. New Access Token Received:

    • The app updates its stored access token with the new one.

    • No need to re-enter your credentials, ensuring a seamless user experience.

Benefits of Refresh Tokens:

  • Improved User Experience: No need to re-login frequently, maintaining seamless access.

  • Enhanced Security: Short-lived access tokens limit potential damage if compromised.

  • Reduced Server Load: Fewer authentication requests as existing tokens are refreshed silently.

Examples of Usage:

  • Social media apps: Stay logged in across devices without constant logins.

  • Email clients: Continuously sync inbox without re-entering passwords.

  • Online banking platforms: Maintain secure access while performing financial transactions.

Refresh tokens aren't without their complexities:

  • Security Concerns: Require careful storage and protection to prevent unauthorized access.

  • Token Revoking: Mechanisms needed to revoke refresh tokens in case of security breaches or account compromise.

Overall, refresh tokens offer a valuable tool for managing user sessions, balancing security and convenience. Understanding their role and usage helps ensure a secure and seamless online experience.

Here is an example of generating refresh token using JSON Web Token :

This code will only work if you have already made your *userSchema*

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

All these things I have learnt from Hitesh Choudhary sir's Chai aur Javascript Backend series on his channel Chai aur Code . It is a magnificent playlist for learning backend development from scratch. Sir always teaches each topic very deeply and in simple way. So I wanna thank Hitesh Choudhary sir for this amazing learning experience.

Also this is my first article on hashnode, I don't know much about article writing. All these thing are my own notes that I have made from the video Access Token and Refresh Token. I hope its decent. Thank you.