Python

Secure Password Hashing and JWT Authentication in Python from Scratch

Authentication is one of those things that looks simple when you first start building an API. A user registers with an email and password, logs in, and…

D
DevByteTechnical Author
Published
20 min read3 views
Secure Password Hashing and JWT Authentication in Python from Scratch

Authentication is one of those things that looks simple when you first start building an API. A user registers with an email and password, logs in, and receives a token to access protected endpoints. A few routes later, the application appears to be working perfectly.

But building authentication that works and building authentication that is secure are two different things.

What happens if someone gets access to your database? What if your application stores passwords as plain text? Can a user modify a JWT token and access another account? What happens when an access token expires or a signing key gets exposed?

These are the questions we need to consider when implementing authentication in a real application.

In this guide, we'll build password hashing and JWT authentication in Python from scratch, using FastAPI for the API layer. We'll cover password hashing, verification, token generation, token validation, protected endpoints, and common security mistakes.

The goal isn't to create a complete authentication framework. It's to understand what's happening behind the scenes so you can make better decisions when building production applications.

1. Understanding Authentication vs. Authorization

Before writing code, let's clarify two concepts that are often used interchangeably.

Authentication answers the question: Who are you?

For example, a user provides an email address and password. The application verifies those credentials and establishes the user's identity.

Authorization answers the question: What are you allowed to do?

A logged-in user might be allowed to view their own profile but not access an administrator's dashboard.

A typical authentication flow looks like this:

  1. A user registers with an email and password.

  2. The application validates the input.

  3. The password is hashed before being stored in the database.

  4. The user logs in with their credentials.

  5. The application verifies the submitted password against the stored hash.

  6. If the credentials are valid, the application issues a signed JWT access token.

  7. The client sends the token with subsequent requests.

  8. The API verifies the token before allowing access to protected resources.

Notice that the original password is never supposed to be stored in the database.

That's the first security principle we'll implement.

2. Why Passwords Should Never Be Stored as Plain Text

Imagine a database table containing these records:

Email

Password

alex@example.com

alex123

sam@example.com

password123

john@example.com

john@2026

If an attacker gains access to this database, every account is immediately compromised.

There is another problem. People frequently reuse passwords across different websites. A password exposed by one application might allow an attacker to access another service.

This is why passwords should be stored as password hashes, not as plain text or reversible encryption.

What is password hashing?

Hashing transforms an input into a fixed-format output using a mathematical function.

For example:

Password: MySecurePassword123!

Hash:
$argon2id$v=19$m=65536,t=3,p=4$...

The actual output depends on the algorithm, its parameters, and a randomly generated salt.

A secure password-hashing algorithm is designed to make guessing passwords expensive.

Unlike encryption, password hashing isn't intended to be reversed. When a user logs in, the application verifies the submitted password against the stored hash rather than decrypting the hash to recover the original password.

Why not use SHA-256?

Python makes it easy to calculate a SHA-256 hash:

import hashlib

password = "MySecurePassword123!"
hashed_password = hashlib.sha256(
    password.encode("utf-8")
).hexdigest()

print(hashed_password)

However, SHA-256 alone is not suitable for storing passwords.

It's designed to be fast. An attacker with a stolen database can try enormous numbers of password guesses quickly, especially with specialized hardware.

For password storage, use a dedicated password-hashing algorithm such as:

  • Argon2id: A strong general-purpose choice for modern applications.

  • scrypt: Designed to make password guessing expensive in memory and computation.

  • bcrypt: A widely used password-hashing algorithm with established tooling.

For this project, we'll use Argon2id through the pwdlib library.

3. Setting Up the Python Project

Let's create a small FastAPI application.

Create a project directory:

mkdir python-jwt-auth
cd python-jwt-auth

Create a virtual environment:

python -m venv .venv

Activate it on macOS or Linux:

source .venv/bin/activate

On Windows, use:

.venv\Scripts\activate

Install the required dependencies:

pip install fastapi "uvicorn[standard]" pwdlib argon2-cffi PyJWT email-validator

We'll use:

Package

Purpose

FastAPI

Build HTTP endpoints

Uvicorn

Run the application

pwdlib

Provide password-hashing utilities

argon2-cffi

Provide the Argon2 implementation

PyJWT

Create and verify JWTs

email-validator

Validate email addresses through Pydantic's email type

Create the following project structure:

python-jwt-auth/
├── main.py
└── .env

For now, we'll keep the example in a single Python file so the authentication flow is easy to understand. In a larger application, you would separate configuration, database operations, schemas, and authentication services.

4. Implementing Secure Password Hashing

Let's start with password hashing and verification.

Create main.py and add:

from pwdlib import PasswordHash

password_hash = PasswordHash.recommended()


def hash_password(password: str) -> str:
    return password_hash.hash(password)


def verify_password(
    plain_password: str,
    stored_hash: str,
) -> bool:
    return password_hash.verify(
        plain_password,
        stored_hash,
    )

That's the foundation of our password security.

Hash a password

password = "MySecurePassword123!"

hashed = hash_password(password)

print(hashed)

The returned value contains the information needed to verify the password later, including the algorithm parameters and salt.

You should store this complete hash string in your database.

Verify a password

When a user logs in, the application retrieves the stored hash associated with the account and checks the submitted password:

submitted_password = "MySecurePassword123!"

if verify_password(submitted_password, hashed):
    print("Password is correct")
else:
    print("Invalid password")

The verification function performs the appropriate hashing operation and checks the result.

You don't need to generate a new salt manually for every registration. The password-hashing library handles this as part of the hashing process.

Why do two identical passwords produce different hashes?

Consider hashing the same password twice:

first_hash = hash_password("MySecurePassword123!")
second_hash = hash_password("MySecurePassword123!")

print(first_hash == second_hash)

The result should be:

False

This is expected.

Argon2id uses a random salt, so the same password can produce different stored hashes.

During login, the verification function reads the salt and parameters from the stored hash and uses them to verify the submitted password.

This makes precomputed hash attacks more difficult.

A few password-storage rules

Keep these rules in mind:

  • Never store plain-text passwords.

  • Never log passwords or password hashes unnecessarily.

  • Don't use MD5 or plain SHA-256 for password storage.

  • Don't create your own password-hashing algorithm.

  • Use a maintained password-hashing library.

  • Choose hashing parameters appropriate for your production environment.

  • Rate-limit login attempts to reduce online password guessing.

Argon2id is a good starting point, but its memory and computation settings should be tested against your server's resources and expected authentication traffic.

5. Understanding JWT Authentication

Now that passwords can be stored securely, we need a way to authenticate requests after login.

One common approach is JSON Web Tokens, usually called JWTs.

A JWT is a compact token that can carry claims about a user or another subject. It's commonly used to represent authentication information between a client and an API.

A JWT generally consists of three parts:

header.payload.signature

For example:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
.
eyJzdWIiOiIxMjMiLCJleHAiOjE5MDAwMDAwMDB9
.
signature

The example is illustrative rather than a complete token.

Header

The header describes the token type and signing algorithm.

{
  "alg": "HS256",
  "typ": "JWT"
}

Payload

The payload contains claims.

For example:

{
  "sub": "user-123",
  "exp": 1900000000
}

Here:

  • sub identifies the token's subject.

  • exp represents the token's expiration time.

You can include other claims, but only include information that is genuinely needed.

Signature

The signature allows the server to detect whether the signed token has been altered.

For an HMAC-signed JWT, the signature is generated using a secret key and the encoded header and payload.

If someone modifies the payload without being able to produce a valid signature, token verification should fail.

Important: A signed JWT is not automatically encrypted. Its payload is normally readable by anyone who possesses the token. Never put passwords, API keys, or other secrets in JWT claims.

6. Configure the JWT Signing Secret

JWT security depends heavily on the signing key.

For this example, we'll use an HMAC-based signing algorithm, HS256. The same secret must be used to sign and verify tokens.

Generate a strong secret locally:

python -c "import secrets; print(secrets.token_urlsafe(48))"

Create a .env file:

JWT_SECRET_KEY=replace_this_with_your_generated_secret
JWT_ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=15

Replace the example value with the generated secret.

Do not commit your real .env file to Git. Add it to .gitignore:

.env
.venv/
__pycache__/

For a simple local example, we'll load the secret from an environment variable.

In production, use your deployment platform's secret-management system or a dedicated secrets manager.

We also need to ensure that the application fails to start if the secret is missing or obviously a placeholder.

Add this configuration near the top of main.py:

import os
from datetime import datetime, timedelta, timezone

import jwt
from fastapi import HTTPException, status

JWT_SECRET_KEY = os.getenv("JWT_SECRET_KEY")

JWT_ALGORITHM = os.getenv(
    "JWT_ALGORITHM",
    "HS256",
)

ACCESS_TOKEN_EXPIRE_MINUTES = int(
    os.getenv("ACCESS_TOKEN_EXPIRE_MINUTES", "15")
)

if (
    not JWT_SECRET_KEY
    or JWT_SECRET_KEY == "replace_this_with_your_generated_secret"
    or len(JWT_SECRET_KEY) < 32
):
    raise RuntimeError(
        "Set a strong JWT_SECRET_KEY environment variable."
    )

if JWT_ALGORITHM != "HS256":
    raise RuntimeError(
        "This example supports HS256 only."
    )

if ACCESS_TOKEN_EXPIRE_MINUTES <= 0:
    raise RuntimeError(
        "Token expiration must be greater than zero."
    )

Note: Python's os.getenv() does not automatically load values from .env. Export the variables in your shell, or use a configuration library such as pydantic-settings to load environment configuration.

For example, on macOS or Linux:

export JWT_SECRET_KEY="paste-your-generated-secret-here"
export JWT_ALGORITHM="HS256"
export ACCESS_TOKEN_EXPIRE_MINUTES="15"

This avoids accidentally running the application with a missing or placeholder signing key.

7. Creating JWT Access Tokens

Let's create a function that generates a signed access token for an authenticated user.

Add the following function to main.py:

def create_access_token(
    subject: str,
    expires_delta: timedelta | None = None,
) -> str:
    now = datetime.now(timezone.utc)

    expires_at = now + (
        expires_delta
        or timedelta(
            minutes=ACCESS_TOKEN_EXPIRE_MINUTES
        )
    )

    payload = {
        "sub": subject,
        "iat": now,
        "exp": expires_at,
    }

    token = jwt.encode(
        payload,
        JWT_SECRET_KEY,
        algorithm=JWT_ALGORITHM,
    )

    return token

Let's understand what's happening here.

The sub claim

The sub claim identifies the token's subject. In this example, we'll use the user's database ID.

Using a stable identifier is generally better than using an email address because email addresses can change.

The iat claim

iat stands for issued at. It records when the token was created.

The exp claim

exp stands for expiration time. Once the token expires, a correctly configured JWT verification process rejects it.

In this example, access tokens expire after 15 minutes.

Short-lived access tokens reduce the period during which a stolen token can be used. They don't, by themselves, prevent theft or provide immediate revocation.

Generate a token

For testing:

token = create_access_token("user-123")

print(token)

The function returns a signed JWT string.

In a real application, call this function only after successfully verifying the user's credentials.

Never allow a client to choose an arbitrary subject when requesting an access token.

8. Verifying JWT Tokens Securely

Generating tokens is only half the job. The API must verify each token before trusting its claims.

Add this function:

def decode_access_token(token: str) -> dict:
    try:
        payload = jwt.decode(
            token,
            JWT_SECRET_KEY,
            algorithms=[JWT_ALGORITHM],
            options={
                "require": ["sub", "iat", "exp"],
            },
        )

        subject = payload.get("sub")

        if not isinstance(subject, str) or not subject:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Invalid authentication token",
            )

        return payload

    except jwt.InvalidTokenError:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid or expired authentication token",
            headers={"WWW-Authenticate": "Bearer"},
        )

Notice that the accepted algorithm is explicitly specified:

algorithms=[JWT_ALGORITHM]

This is important. The server should not blindly trust the algorithm declared inside an incoming token.

The verification process checks the signature and expiration and ensures that required claims are present.

We also validate the subject because the application needs a meaningful user identifier.

Why not just decode the token?

Decoding a JWT without verifying its signature does not establish that the token is authentic.

An attacker could create a token containing arbitrary claims.

Always verify the signature and validate the claims your application depends on before using them for authentication or authorization.

9. Building Registration and Login Endpoints

Now let's connect the password and JWT functions to FastAPI.

For this tutorial, we'll use an in-memory dictionary to keep the code focused on authentication.

This is only for demonstration. It loses data when the application restarts and isn't suitable for a production application. A real system should use a database with a unique constraint on normalized email addresses.

Add the imports:

from fastapi import FastAPI, HTTPException, status
from pydantic import BaseModel, EmailStr, Field

Create the application and a temporary user store:

app = FastAPI(
    title="Python JWT Authentication API"
)

users: dict[str, dict] = {}

We'll use the normalized email address as the dictionary key in this demonstration.

Define request schemas

class RegisterRequest(BaseModel):
    email: EmailStr
    password: str = Field(
        min_length=12,
        max_length=128,
    )


class LoginRequest(BaseModel):
    email: EmailStr
    password: str = Field(
        min_length=1,
        max_length=128,
    )

The registration schema requires at least 12 characters. This is an example policy, not a universal requirement; your policy should consider your threat model, password manager support, and applicable standards.

The maximum length also prevents unnecessarily large input from being passed to the password-hashing function.

Don't silently truncate passwords. If an input exceeds your supported limit, reject it clearly.

Registration endpoint

@app.post(
    "/register",
    status_code=status.HTTP_201_CREATED,
)
def register_user(data: RegisterRequest):
    email = str(data.email).strip().lower()

    if email in users:
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail="Unable to register with this email",
        )

    user = {
        "id": str(len(users) + 1),
        "email": email,
        "hashed_password": hash_password(data.password),
    }

    users[email] = user

    return {
        "message": "Registration successful",
        "user": {
            "id": user["id"],
            "email": user["email"],
        },
    }

Let's walk through the important steps.

First, we normalize the email address for this simple demonstration. A production implementation should use a consistent email-normalization policy and enforce uniqueness at the database level.

Second, we check whether the account already exists.

Third, we hash the password before storing it.

Finally, we return the user's ID and email without exposing the stored password hash.

In production, be careful about revealing whether an email address is already registered. Depending on your threat model, generic responses can help reduce account enumeration.

Login endpoint

Now let's authenticate the user.

@app.post("/login")
def login_user(data: LoginRequest):
    email = str(data.email).strip().lower()

    user = users.get(email)

    if not user or not verify_password(
        data.password,
        user["hashed_password"],
    ):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid email or password",
            headers={"WWW-Authenticate": "Bearer"},
        )

    access_token = create_access_token(
        subject=user["id"]
    )

    return {
        "access_token": access_token,
        "token_type": "bearer",
        "expires_in": ACCESS_TOKEN_EXPIRE_MINUTES * 60,
    }

The endpoint follows a straightforward process:

  1. Normalize the submitted email address.

  2. Find the corresponding user.

  3. Verify the submitted password against the stored hash.

  4. Return the same generic error for an unknown user and an incorrect password.

  5. Generate an access token after successful verification.

The generic error avoids directly telling an attacker whether an account exists.

However, response wording alone doesn't prevent account enumeration. Differences in response time, rate limits, or other behavior can still reveal information.

Also, this simple example doesn't perform a password-hashing operation for unknown users, so timing may differ between unknown accounts and incorrect passwords. Production authentication systems should consider this and use suitable rate limiting and other mitigations.

10. Protecting Routes with FastAPI Dependencies

We can now register users and issue tokens. The next step is protecting API endpoints.

FastAPI provides dependency injection, which makes it convenient to validate credentials before running a route handler.

Add these imports:

from typing import Annotated

from fastapi import Depends
from fastapi.security import (
    HTTPAuthorizationCredentials,
    HTTPBearer,
)

Create a bearer-token security dependency:

bearer_scheme = HTTPBearer()

Now create a dependency that validates the token and retrieves the corresponding user.

def get_current_user(
    credentials: Annotated[
        HTTPAuthorizationCredentials,
        Depends(bearer_scheme),
    ],
):
    payload = decode_access_token(
        credentials.credentials
    )

    user_id = payload["sub"]

    user = next(
        (
            stored_user
            for stored_user in users.values()
            if stored_user["id"] == user_id
        ),
        None,
    )

    if user is None:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid authentication token",
            headers={"WWW-Authenticate": "Bearer"},
        )

    return user

This dependency does two important things.

First, it verifies the JWT and extracts its subject.

Second, it checks that the referenced user still exists.

Checking the user against the current data store means a token won't automatically remain valid if its user record has been deleted. In a real application, this lookup should be an indexed database query.

Create a protected endpoint

@app.get("/me")
def get_profile(
    current_user: Annotated[
        dict,
        Depends(get_current_user),
    ],
):
    return {
        "id": current_user["id"],
        "email": current_user["email"],
    }

If the request contains a valid token, FastAPI calls the endpoint and returns the user's profile.

If the token is missing, malformed, expired, or invalid, the request is rejected before the route handler runs.

This is one of the main benefits of using dependencies: authentication logic can be reused across many routes instead of being duplicated in every endpoint.

11. Running and Testing the Application

Your main.py should now contain the imports, configuration, password functions, JWT functions, request schemas, endpoints, and authentication dependency introduced above.

Start the application:

uvicorn main:app --reload

Open FastAPI's interactive documentation at:

http://127.0.0.1:8000/docs

You can test the complete flow without building a frontend.

Step 1: Register a user

Send a POST request to /register:

{
  "email": "alex@example.com",
  "password": "MyStrongPassword123!"
}

Expected response:

{
  "message": "Registration successful",
  "user": {
    "id": "1",
    "email": "alex@example.com"
  }
}

The application stores the password hash, not the original password.

Step 2: Log in

Send a POST request to /login:

{
  "email": "alex@example.com",
  "password": "MyStrongPassword123!"
}

A successful response contains an access token:

{
  "access_token": "your-signed-jwt-token",
  "token_type": "bearer",
  "expires_in": 900
}

The actual token will be a long string. Don't copy the illustrative placeholder above into a request.

Step 3: Access the protected endpoint

Send a GET request to /me.

Include this HTTP header:

Authorization: Bearer your-signed-jwt-token

If the token is valid, the response should look like this:

{
  "id": "1",
  "email": "alex@example.com"
}

In FastAPI's interactive documentation, click Authorize and enter the token if prompted. You generally enter the token itself when the interface already manages the Bearer prefix.

Step 4: Test invalid credentials

Try logging in with an incorrect password:

{
  "email": "alex@example.com",
  "password": "WrongPassword123!"
}

The API should return 401 Unauthorized.

Step 5: Test an expired token

For a quick test, create a token with an expiration time in the past:

expired_token = create_access_token(
    subject="1",
    expires_delta=timedelta(seconds=-1),
)

Use that token to call /me. Verification should reject it.

These tests confirm the basic authentication flow works as expected.

12. Access Tokens vs. Refresh Tokens

Our current implementation issues short-lived access tokens.

When an access token expires, the user must log in again unless the application implements a refresh-token flow.

For applications with longer sessions, refresh tokens can provide a better user experience.

An access token is usually short-lived and sent with API requests. A refresh token is used to obtain a new access token without requiring the user to enter their password again.

A typical design looks like this:

  1. The user logs in successfully.

  2. The server issues a short-lived access token.

  3. The server also issues a refresh token with a longer lifetime.

  4. When the access token expires, the client submits the refresh token to a dedicated endpoint.

  5. The server validates the refresh token and issues a new access token.

  6. Depending on the design, the server rotates the refresh token and invalidates the previous one.

Refresh tokens need their own security controls.

For example, you can store a hash of each refresh token in the database, associate it with a user and session, track expiration, and revoke it when the user logs out or a suspicious event occurs.

For browser-based applications, storing refresh tokens in HttpOnly, Secure cookies with an appropriate SameSite policy can reduce exposure to JavaScript. Cookie-based authentication also requires careful consideration of cross-site request forgery (CSRF).

Avoid putting long-lived refresh tokens in browser local storage without evaluating the risks. JavaScript-accessible storage can expose tokens if an attacker exploits cross-site scripting.

Don't add refresh tokens just because they are common. Start with a short-lived access token if it meets your application's needs, then implement a properly designed refresh flow when persistent sessions are required.

13. Common JWT Authentication Mistakes

JWTs are useful, but they don't automatically make an application secure.

Here are several mistakes worth avoiding.

Mistake 1: Using a weak signing secret

A short or predictable secret can make a symmetric signing system vulnerable to guessing attacks.

Generate a cryptographically random secret and keep it private.

Don't use values such as:

secret
password123
myjwtkey

Use a securely generated key and rotate it according to your application's operational requirements.

Mistake 2: Accepting arbitrary JWT algorithms

Never allow the incoming token to dictate which algorithms your server accepts.

Use an explicit algorithm allowlist and configure the verifier consistently with the token issuer.

For example:

jwt.decode(
    token,
    JWT_SECRET_KEY,
    algorithms=["HS256"],
)

For this example, the issuer and verifier use the same secret.

In systems with multiple services, asymmetric signing algorithms such as RS256 or EdDSA may be a better fit because services can verify tokens using public keys without receiving the private signing key.

Mistake 3: Putting sensitive information in the payload

JWT payloads are not automatically confidential.

Avoid including:

  • Passwords

  • Password hashes

  • API keys

  • Private customer information

  • Secrets or credentials

Keep the token payload small and include only claims the application needs.

Mistake 4: Creating tokens that never expire

A stolen token that never expires can remain useful indefinitely unless another control invalidates it.

Set a reasonable expiration time and build a revocation strategy appropriate to your application.

Mistake 5: Trusting token claims without authorization checks

A valid token establishes that its claims were signed by a trusted issuer and passed verification. It doesn't automatically grant access to every resource.

For example, a user with a valid token should not be able to retrieve another user's private records merely by changing a user ID in the URL.

Always check whether the authenticated user is authorized to access the requested resource.

Mistake 6: Ignoring brute-force attacks

An attacker may repeatedly submit guessed passwords to a login endpoint.

Protect login and registration endpoints with rate limiting, sensible monitoring, and abuse detection.

Consider account lockout or progressive delays carefully. Poorly designed lockout policies can let attackers deliberately deny service to legitimate users.

Mistake 7: Logging authentication secrets

Never write submitted passwords, complete bearer tokens, refresh tokens, or signing keys to application logs.

Logs are frequently accessible to more people and systems than the primary database. Treat them as sensitive operational data.

14. What Should Change Before Production?

The implementation we've built demonstrates the core concepts, but it is not a complete production authentication system.

Before deploying an application, address the following areas.

Area

Demonstration

Production approach

User storage

In-memory dictionary

Persistent database

Password hashing

Argon2id via pwdlib

Argon2id with tested parameters and a migration plan

Duplicate accounts

In-memory lookup

Database unique constraint and consistent normalization

JWT secret

Environment variable

Secret manager or secure deployment configuration

Access token

Short-lived JWT

Defined expiration and key-rotation strategy

Token revocation

No revocation mechanism

Session or revocation design where required

Login protection

No rate limiting

Rate limits, monitoring, and abuse controls

Authorization

Authenticated profile route

Role, permission, and resource-ownership checks

Transport

Local development

HTTPS in deployed environments

Logging

Basic framework behavior

Structured logs without credentials or tokens

Testing

Manual requests

Automated tests for valid and invalid authentication flows

There are also a few implementation details to consider.

Database transactions: Registration should use a database transaction and a unique constraint to avoid duplicate accounts under concurrent requests.

Password changes: When a user changes their password, decide whether existing sessions should be invalidated. JWTs don't automatically become invalid simply because the password changes.

Token revocation: Stateless access tokens are convenient, but immediate revocation generally requires additional server-side state, short token lifetimes, or another mechanism.

Key rotation: If your signing key is compromised, you need a plan to stop trusting tokens signed with that key. A key identifier (kid) and controlled key-rotation process can help in systems that support multiple active verification keys.

HTTPS: Always use HTTPS in production so credentials and bearer tokens are protected in transit.

CORS: Configure Cross-Origin Resource Sharing for the specific frontend origins that need API access. CORS is a browser security mechanism, not a replacement for authentication or authorization.

Dependency updates: Keep FastAPI, PyJWT, Argon2 libraries, and other dependencies updated, and test security-sensitive upgrades before deploying them.

15. A Note About JWTs and Logout

One common misunderstanding is that deleting a token from the frontend invalidates it on the server.

With a purely stateless JWT access-token design, the server can continue accepting a token until it expires, provided its signature and claims remain valid.

Removing the token from the client prevents that client from sending it again, but it doesn't invalidate a stolen copy.

If your application requires immediate logout, account-wide session termination, or revocation after a security incident, consider short-lived access tokens combined with server-managed refresh sessions or a carefully designed revocation mechanism.

The correct approach depends on the application's risk level and user experience requirements.

For a small internal service, a short-lived access token may be sufficient. For a financial application or a platform with sensitive personal data, more comprehensive session management is usually necessary.

Conclusion

Secure password hashing and JWT authentication are foundational parts of backend development. They become easier to implement correctly when you understand the purpose of each component instead of treating authentication as a collection of library functions.

In this guide, we used Argon2id to hash passwords, verified credentials during login, generated signed JWT access tokens, validated tokens, and protected a FastAPI endpoint with dependency injection.

We also covered why plain SHA-256 isn't appropriate for password storage, why JWT payloads shouldn't contain secrets, why access tokens need expiration, and why authentication alone doesn't guarantee authorization.

The most important takeaway is simple: use established security libraries, keep secrets out of your code and logs, validate tokens explicitly, and never treat a valid token as permission to access every resource.

As your application grows, move the example's in-memory user store into a database, add automated security tests, implement appropriate rate limits, and design session management around your application's actual requirements.

Understanding these fundamentals will help you build authentication systems that are not only functional but also much easier to maintain and secure.

D
DevByteAuthor

Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.

Keep Exploring

Related Engineering Dispatches

More guides and architectural patterns you might find valuable.

Browse All Articles↘