img of Token Based Authentication
Security

Token Based Authentication

Jan 12, 2025
7 min read

A few days ago, I wrote a post talking about how JWT tokens work. I decided to explore more this topic and write some posts about authentication and authorization techniques and standards. This post will be the first of them. Today we will talk about token-based authentication.

What is a token?

When it comes to authentication and authorization, you’ve probably heard the term token thrown around a lot. But what exactly does it mean, and why is it so important in modern web applications?

A token is a piece of data that represents something important in the world of security—like your identity or the permissions you have within a system. Think of it as a digital key that grants you access to certain areas of an app or website. When you log in, for instance, the system generates a token that proves who you are. You then use that token to access protected resources without needing to re-enter your credentials each time.

Tokens can vary in form. They might be random strings of characters or more structured data like a JSON Web Token (JWT). In any case, they carry certain pieces of information about the user or the session that the server can verify. It’s important that these tokens be kept secret—like how you wouldn’t want anyone stealing your carnival ticket—so that only you (or your application) can use them to access protected resources.

How does token-based authentication work?

You sign into a website—maybe something like your favorite email service or a web-based project management tool—and you stay logged in for a while without constantly re-entering your password. Ever wonder how that works?

  1. Initial Login Request: When you first arrive at the website and click “Log In,” you typically provide your username (or email) and password. This information is sent securely (over HTTPS) to the server.
  2. Server Verifies Credentials: The server checks your credentials against its user database. If you typed the correct password for the given username, then the server trusts that you are indeed that user.
  3. Server Generates a Token: Once the server is satisfied with your credentials, it creates a token. This token might include data such as your user ID, roles or permissions, and an expiration time.
  4. Server Sends the Token Back to You: The server sends the token back in its response, and your browser (or the application you’re using) stores that token somewhere. Typically, a web app will store it in local storage or session storage, while mobile apps might store it in a secure location on the device.
  5. Subsequent Requests: Every time you make a new request (e.g., clicking on a new page or calling an API endpoint), your client includes the token in the request header (commonly in the Authorization header as something like Bearer <token>).
  6. Server Validates the Token: The server checks the token to ensure it’s still valid and not expired. If it’s valid, it grants you access. You won’t need to re-enter your password because the token already serves as proof of your identity.

It’s a neat system because you only hand over your password once. After that, you just show your “ticket” (token) every time you want to do something. That means less hassle for you and greater security, as your password isn’t constantly bouncing around the internet.

Here’s a visual representation of the token-based authentication flow:

Token expiration and renewal

You might be thinking, “If I have a token, does that mean I can keep it forever and stay logged in forever?” The answer is no—at least, not usually. Tokens often have an expiration time for security reasons. If a token is stolen by someone else, you don’t want them to be able to use it indefinitely.

Most systems assign a relatively short lifetime to tokens, such as a few minutes or hours. If your token is only valid for 15 minutes, for instance, that means after 15 minutes, you’ll need a new token to keep using the service without being forced to log in again. However, if you’re actively using the application, you usually won’t notice any interruption because:

  1. Refresh Tokens: Many systems use a “refresh token” mechanism. When the short-lived token is about to expire, the client app quietly requests a new token from the server. The request includes a refresh token (another type of token) that proves you’re already authenticated. If the refresh token is valid, the server issues a new short-lived token without making you re-enter your password.
  2. Longer Session, Less Re-Login: This means you can have extended or persistent sessions without storing a single token that never expires. That’s crucial for security. After all, if you had a token that lasted forever, and it got leaked, an attacker would have perpetual access to your account.

In other words, expiration and renewal processes add layers of protection while still being convenient. You might have noticed that some services ask you to log in again if you’ve been inactive for too long or if your refresh token expires. That’s all part of token-based authentication working to keep your account safe.

Now, you might be thinking, “How does token-based authentication differ from the classic cookie-based approach?” You’ve probably heard about cookies—small pieces of data stored by your browser. Cookies have been around for a while and have historically been used to keep track of your session on a website.

We can compare the two approaches in a few key areas:

AreaCookie-Based AuthenticationToken-Based Authentication
Storage and RetrievalYour session ID is stored in a cookie, and you send that cookie automatically with every request. The server maintains a session state (like in a database or memory) that maps the session ID to your user data.The client (your browser or app) stores the token (often in localStorage or sessionStorage, or sometimes in a secure cookie). It sends this token in an Authorization header (or another method) with every request. The server verifies the token without needing to consult a session store.
ScalabilityBecause the server keeps session data, it might require a sticky session setup or a shared session store if the app runs on multiple servers.The server is largely stateless. All necessary data for authentication is within the token. This makes it easy to scale to multiple servers or microservices without sharing session data.
SecurityIf cookies aren’t set with the right flags (HttpOnly, Secure, SameSite), they can be more susceptible to XSS (Cross-Site Scripting) or CSRF (Cross-Site Request Forgery) attacks.Storing tokens in localStorage or sessionStorage can also be vulnerable to XSS if not done carefully. CSRF is generally less of an issue for tokens because they’re not automatically sent by the browser, but you still need to handle other security aspects.
Usage Across DomainsCookies are typically tied to a specific domain. This can be a bit limiting if you’re working on multiple subdomains or cross-domain setups.Since tokens are sent in the header, you can more easily work with different domains and platforms, such as mobile apps, single-page applications, or microservices.

Overall, token-based authentication provides more flexibility and scalability, especially if you’re building modern, distributed, or cloud-based applications. But cookie-based authentication can still be perfectly fine for many traditional web apps. It really comes down to your specific needs and preferences. Some people even combine them—using cookies to store tokens securely on the client side.

© 2025 Programmer Codex

GitHub