Everything You Always Wanted to Know About authentication* (*But Were Afraid to Ask)

How does authentication work? How can it be implemented securely? Who saves sessions? How long do they last? These are questions I’ve been asked frequently, and I hope to answer them comprehensively in this post.

In This Article:

Sign in

When a user registers for the first time, they enter a username (email address is often used instead) and a password. The password is hashed on the server and saved in the database. It’s clear here that it’s crucial that the credentials are sent via secure https.

The user arrives at the site and logs in, then re-enters their username (or email) and password. The server compares the hash of the password sent with the one saved in the database, and if they match, the user is authenticated.

woody-allen.jpg Everything You Always Wanted to Know About Sex* (*But Were Afraid to Ask), Woody Allen 1972

📕 Vocabulary: A HASH is the result of a mathematical function that transforms data into a fixed-length string. The function is irreversible, which is why passwords are saved this way. There are several functions with different security levels that are used to generate hashes.

2FA/MFA (Two-factor/Multi-factor authentication)

Basic login can be further secured by adding at least one independent factor, so that the account remains secure even if the password is compromised. It’s commonly said that factors are of three types: something you know (E.g. password or pin), something you have (E.g. phone or key), something you are (E.g. biometric recognition). Let’s quickly look at the most common ones:

  • SMS/EMAIL OTP: The server generates a random number, sends it to the user via SMS or Email, the user copies it into the application and if it is correct they are authenticated.
  • HOTP/TOTP: A third party (e.g. an authenticator app like Google Authenticator) shares a secret key with the server, which generates a temporary time-based code (TOTP e.g. every 30 seconds) or an event-based code (HOTP) that is verified by the server.
  • Push-based Authentication: Here too, we have two devices sharing a secret key. The server generates a challenge, a set of data representing the login attempt (device, IP, etc.), and sends it to the user via push notification. When the user confirms access, the challenge is signed with the secret key and sent to the server, which verifies it and authorizes access. This is how Google Authenticator works.
  • Hardware token: It’s a dedicated physical device (USB stick, smart card, etc.) that implements a factor. It can be an OTP and therefore generate a time-based or event-based key, or it can contain a private key capable of signing a challenge.

📕 Vocabulary: OTP (One-Time Password) is a temporary code that the user enters manually to authenticate themselves.

Authentication status

Once the user has been identified and authorized, this information must be retained for a reasonable amount of time so that they can perform actions without having to enter their password each time. This is usually the part that raises the most questions. Let’s try to explain the available strategies in a simple way.

The authentication status can be saved:

Many complex systems use hybrid approaches to maximize security

Session-based authentication

Where the authentication state is persisted on the server

After sign in, the server creates a session and saves it to the file system, the database or Redis (the gold standard is Redis). The session contains an ID, the user’s roles or permissions, a timestamp, and the login status. The session has a time validity (e.g. two hours) depending on the implementation

The session ID is sent to the client via cookie which must have the following flags to be secure: HttpOnly, not accessible via JavaScript. Secure, sent only in https. SameSite, not available cross-domain.

The cookie is sent naturally with each request so that responses reflect the correct permissions, and the timestamp is renewed with each request. This way, each request extends the session life.

After a time of inactivity equal to the session validity, the user will have to log in again.

The remember me flag makes the session longer, or also implements Token-based authentication (in this case we have hybrid authentication).

Since identity is proven via cookies, it’s easy to see why this strategy is well suited for monolithic platforms that don’t need to handle cross-domain calls. Indeed, it’s the one adopted by Magento and other e-commerce platforms.

Token-based authentication (JWT)

Where authentication state is maintained on the client

After sign in, the server issues a JWT token (JSON Web Token) containing signed session data. The client saves it in the local storage, session storage, or a cookie and sends it back with each request as the Authorization Bearer. The server doesn’t save any session information, session information is all in the token.

The token is composed of three strings, the header (which indicates the algorithm to be used), the payload (which contains the user data) and a signature calculated via an HMAC (or RSA/ECDSA) function using the header, payload and a global system secret key.

When the server receives a request with the authorization bearer, it recalculates the signature and, if it matches the one in the token, it authorizes the access.

The security aspect lies in the fact that without the secret key, it’s impossible to generate a valid signature, so no one can tamper with the token.

In modern applications the access token is short-lived and replaced when it expires. Here’s how it works: Together with the access token, the server creates a second token, called refresh token. When the access token expires, this token is used to make a call to a specific endpoint, which returns a new access token. This is implemented with some precautions to prevent an attacker from generating infinite access tokens. Typically, refresh tokens are tracked server-side (Redis) and associated with some device information.

Token authentication is particularly suitable for decoupled frontend and backend, headless, microservices, and API-based applications.

📕 Vocabulary: HMAC is an authentication mechanism that uses a hash function together with a secret key.

Delegated authorization

To simplify the user’s life, authentication can be delegated to a third-party service (Google, GitHub, etc.). With the user’s authorization, this service will issue and verify the JWT token.

The most commonly used delegations are based on the Oauth2.0 protocol and Open ID Connect (which provides authentication in addition to authorization).

social-login.png

That’s all

I hope I have helped clear up some doubts

Written by humans
Irene Iaccio

Freelance web developer