Token-Based Authentication with Cookies and JWT Expiration

Introduction

Welcome to the lesson on Token-Based Authentication with Cookies and JWT Expiration. In our previous lesson, we explored account lockout and enumeration prevention, which are crucial for securing web applications. Today, we'll dive deeper into token-based authentication, a key component in modern application security. We'll focus on advanced features like the usage of cookies and token expiration. These concepts are essential for maintaining secure and efficient authentication processes in your applications. Let's get started!

Securing JSON Web Tokens (JWT)

In the previous unit, we focused on only one authentication method: using user credentials, specifically username and password. You already know that JSON Web Tokens (JWT) are commonly used for secure authentication. However, as more resources gain access to an account, the number of potential attack vectors increases. What happens if JWTs are exposed? Here, we present strategies to enhance the security of JWTs.

Limiting Damage from Token Theft

In previous courses, we mainly focused on how attackers can exploit vulnerabilities. However, ensuring security in applications not only includes mitigating the chances of an outage but also focuses on reducing the harm when a breach has already occurred. Imagine that the attacker somehow stole your JWT token (one example is that the engineer posted unnecessary debug results including this data in an online Q&A platform). One way to limit the attacker's actions is to implement a token expiration mechanism.

Implementing Token Expiration

Before this, you may have noticed that we used the following structure to create the token in the '/login' api:

Python
token = jwt.encode({'userId': user.id}, JWT_SECRET_KEY, algorithm='HS256')

As we discussed earlier, this is vulnerable. Token expiration is a critical feature that ensures tokens are valid only for a limited time, reducing the risk of misuse.

from datetime import datetime, timedelta

# Generate token with expiration
token = jwt.encode(
    {
        'userId': user.id,
        'exp': datetime.utcnow() + timedelta(hours=1)  # Token expires in 1 hour
    },
    JWT_SECRET_KEY,
    algorithm='HS256'
)

Here, we set the exp claim to expire in one hour. This limits the window of opportunity for an attacker to use a stolen token.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal