Skip to main content

Command Palette

Search for a command to run...

Talk On AccessToken & RefreshToken:

Guide to Secure Authentication

Published
โ€ข2 min readโ€ขView as Markdown

๐ŸŽŸ๏ธ Imagine This...

You go to a movie theatre.๐Ÿ™‚

  • You get a ticket to watch a movie. Thatโ€™s your access token.

  • But you also have a VIP card in your pocket โ€” if your ticket expires, you flash that card to get a new one. Thatโ€™s your refresh token.

Boom. ๐ŸŽฌ You just understood token-based authentication.

๐Ÿง So, What Exactly Are These Tokens?

โœ…What is an Access Token?

  • ๐Ÿ”‘ Short-lived token

  • ๐Ÿ•’ Used on every API call

  • โš ๏ธ If stolen โ†’ attacker can act as user (temporarily)

    ๐Ÿ” Refresh Token

    • Long-lived (like 7 days)

    • Stored securely (usually in an HTTP-only cookie)

    • Used only to get a new access token

    • Must never be exposed to JavaScript

Why Two Tokens?

๐Ÿ”„ Why Two Tokens?

Because security + user experience need balance.

FeatureAccess TokenRefresh Token
Used every time?โœ… YesโŒ No
Short-lived?โฑ๏ธ Yesโณ No
Safer to expose?โš ๏ธ SomewhatโŒ NEVER
Stored in?Header or cookieHTTP-only cookie
If stolen?๐Ÿ”“ Small damage๐Ÿ”ฅ Big damage

๐Ÿ” Waitโ€ฆ What Are These Tokens Made Of?

Both access and refresh tokens are stored in JWT (JSON Web Token) format.

  • Itโ€™s basically a compact string that carries some data (like your user ID), and is cryptographically signed so that it canโ€™t be tampered with.

  • ๐Ÿง  A JWT has 3 parts:

      header.payload.signature
    

    Example:

      CopyEditeyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
      eyJfaWQiOiIxMjM0NTYiLCJyb2xlIjoidXNlciJ9.
      VZciYXNnNklfdWZlc3Rfc2lnbmF0dXJl
    

    You can decode it at jwt.io to peek inside.

Hereโ€™s a workflow:

๐Ÿ”“ What if tokens are exposed?

If someone gets hold of your access token:

  • They can make API requests on your behalf until it expires.

  • Risk level: moderate
    ๐Ÿ›ก๏ธ Mitigation: Short token lifespan (e.g., 15 mins)

If someone gets your refresh token:

  • They can keep generating new access tokens = full account hijack!

  • Risk level: high
    ๐Ÿ›ก๏ธ Mitigation:

    • Store in httpOnly cookie

    • Rotate tokens on use

    • Invalidate on logout

      ๐Ÿ” Security Measures You Should Always Use

      โœ… Store refresh tokens in httpOnly, secure cookies
      โœ… Rotate refresh tokens after each use
      โœ… Clear tokens on logout
      โœ… Validate token against DB before use
      โœ… Add expiry to both tokens

  • ~Auth tokens are like keys to your kingdom โ€” treat them like secrets, not souvenirs