Designing a Secure Session Token Design Pattern

Table of Contents

Designing a Secure Session Token Design Pattern

Introduction

In modern web applications, authentication has evolved well beyond simple username–password logins. We now rely on JSON Web Tokens (JWTs), OAuth 2.0,
and federated identity systems to manage user sessions securely and at scale. Secure authentication and secure session management are critical for protecting
user credentials and session ids from threats such as session fixation, hijacking, and prediction attacks. However, one persistent problem remains in web
applications: insecure session token storage in the user's browser. This causes exposure of web applications to cross site scripting attacks, where tokens stored in
local storage or session storage can be stolen or manipulated, leading to session hijacking and other security breaches. Attackers may be able to gain access to
information about the internal systems, infrastructure, and operations that could result in vulnerability of discovery.

Problem Statement: Local Storage Session Token Vulnerability

Most web applications use access tokens to validate authentication sessions issued by backend services and identity providers like Okta, Salesforce, and others.
These tokens authorize api requests to the appropriate Application Programming Interfaces (APIs), and are often attached to subsequent requests from the
frontend to maintain secure access and session integrity. Session cookies with secure attribute and HttpOnly flags are recommended to protect session data
during transit and prevent interception.

These are some problems that are caused while storing session tokens in local storage.

  • Misplaced Trust in the Browser Environment

Now a days developers think that storing sessions in a local browser is safe, but it is inherently not considered safe because we are connected to the Internet and
cloud. It is a shared execution context that runs user-installed browser extensions, third-party scripts, and malicious injected scripts (via cross-site scripting). All
the above-mentioned components can execute JavaScript within the same origin as your application, which means they can directly access any data stored in
localStorage, sessionStorage, or non-HttpOnly cookies from our browser storage. That is where the trust boundary is broken. Session tokens that contain sensitive
authentication credentials or PII data, are stored in the browser in an insecure, script-accessible location.

Example of Token Theft via XSS

const SESSION Token = localStorage.getItem(“Dummy_Access_Token”);
fetch (“Respective URL”, {
method: “POST/GET/UPDATE”,
body: Dummy_Access_Token
});

If the application stores an access token in localStorage, a single cross-site scripting flaw can lead to complete account takeover.

  • Stateless Authentication Misuse

Token-based authentication is designed to operate without server-side session tracking, as the token itself carries the necessary information about the user’s
identity and permissions. That part is fine. The problem starts when these tokens are used directly in the browser. Most of them stick around for quite a while,
sometimes minutes, sometimes hours, and they are usually not tied to a device, an IP address, or anything unique. So, if someone manages to grab that token,
they can use it wherever they want. It turns into a password that keeps working until it expires. No extra checks, no limitations just plug it in, and it works. To
prevent misuse, it is essential to enforce session integrity and ensure that only a valid session id is accepted for an established session.

  • Frontend Convenience with Security

Frontends typically cache access tokens, so they can attach them to API calls using the standard authorization: Bearer < token> header. It is convenient for the
User Interface (UI) layer, but it also pushes session-like responsibility onto the browser, which is not a trustworthy environment. Once tokens live in client-side
storage — whether that’s localStorage, sessionStorage, or memory — they are exposed to a much broader attack surface: XSS, browser extensions, token
extraction tools, and even accidental leaks through logs or debugging tools. For each subsequent request, the browser sends the session cookie or token to the
server, which verifies the user's identity and maintains secure access to session data.

  • Absence of Token Lifecycle Controls

Insecure token storage is often accompanied by weak token lifecycle management. It has no refresh rotation mechanism, long-lived access tokens, or missing
revocation checks. This makes the situation worse. Even if a token is stolen, it remains valid for a long period, giving attackers plenty of time to exploit it. The core
issue extends beyond storage to the entire token lifecycle, which is often handled insecurely outside the backend’s direct control. Using a refresh token and
managing sessions securely with a backend component and the token handler pattern helps ensure that tokens are rotated, revoked, and protected according to
best practices.

  • Lack of Separation Between Authentication and Authorization

Many web applications implement authentication (proving identity) and authorization (granting access) into one process that happens entirely in the frontend.

A more secure pattern delegates these responsibilities:

  1. Authentication is majorly handled with a trusted Identity Provider. During the authentication process, the backend component issues a session cookie
    with the secure attribute set, ensuring that the session cookie is only transmitted over HTTPS.
  2. Authorization and session management are handled by the backend server, which acts as the intermediary between the client and Cognito.
  • Monitoring and Logging

Proper monitoring and logging are often overlooked in insecure session token implementations. User logs are essential for detecting suspicious activity, such as
session hijacking or unauthorized access, and help maintain the security of established sessions.

  • Session Expiration

Session expiration is a critical aspect of secure session management. Sessions should have both idle and absolute timeouts, and session data must be invalidated
after session expiration to prevent attackers from reusing old session tokens.

Session Token Properties

A secure session token is the cornerstone of robust session management in any web application. To protect user sessions and sensitive data from unauthorized
access, session tokens must be designed and managed with security as the top priority.

Uniqueness and Randomness: Every session token should be unique and generated using a cryptographically secure pseudorandom number generator (CSPRNG).
This ensures that session identifiers cannot be easily guessed or predicted, significantly reducing the risk of brute-force or guessing attacks. Tokens should be of
sufficient length and complexity to withstand modern attack techniques.

Secure Transmission and Storage: Session tokens must always be transmitted over secure channels, such as HTTPS, to prevent interception by attackers
monitoring user HTTP traffic. On the client side, tokens should be stored using secure mechanisms—preferably in HttpOnly cookies or managed by dedicated
token handler components. This approach prevents access by malicious JavaScript code and mitigates the risk of cross site scripting (XSS) attacks. Avoid storing
tokens in local storage or session storage, as these are accessible to any script running in the user’s browser.

Lifecycle Management and Expiration: To minimize the window of opportunity for session hijacking, session tokens should have a limited lifetime. Implement
session timeouts and expiration mechanisms so that tokens automatically become invalid after a set period or after user inactivity. When a user authenticates,
generate a new session token and immediately invalidate any previous tokens to prevent session fixation attacks. Regularly rotating tokens and using refresh
tokens for extended sessions further enhances security.

Binding and Access Controls: Session tokens should be bound to the user’s browser or device, making it difficult for attackers to reuse stolen tokens from a
different context. Implement same-domain policies and anti-CSRF tokens to protect against cross site request forgery attacks. Access control mechanisms, such as
role-based access control, should be enforced to ensure that only authenticated users with appropriate permissions can access protected resources.

Monitoring and Logging: Robust security measures include monitoring session logs for suspicious activity, such as multiple requests from different locations or
signs of session hijacking. Regularly review session logs to detect and respond to potential security risks, and ensure that session management mechanisms are
functioning as intended.

Token Formats and Protocols: JSON Web Tokens (JWTs) are commonly used as session tokens, providing a compact and secure way to transfer claims between
parties. When using JWTs, ensure they are signed and, if necessary, encrypted to protect sensitive data. OpenID Connect (OIDC) builds on OAuth 2.0 and uses
session tokens to manage user authentication and authorization, offering a scalable solution for modern web applications. OIDC also supports offline access,
allowing users to maintain access to protected resources even when the authorization server is temporarily unavailable.

Secure Session Management Design Pattern with AWS Cognito

The design pattern contains authentication from the client-side session token handling. AWS Cognito provides a secure way to communicate with the web
application via OAuth 2.0 and the Authorization Code Flow.

Step 1: Accessing the Web Application or Service

The web application begins evaluating whether the user already has a valid session or not, once loaded.

Step 2: Checks for an existing Authenticated Session

The web client establishes the existing session / authentication understanding, leveraging the AWS Amplify SDK, while enforcing the application’s authorization
rules for protected routes. The client code also manages session timing and validation for authenticated sessions, ensuring that only valid authenticated sessions
are maintained and reducing the risk of session fixation or token theft.

Step 3: Federated sign-in Flow

If somehow a user is not authenticated with existing sessions, then the web application uses the AWS Amplify federated sign-in flow to redirect them to the
configured Identity Provider (okta, salesforce, etc). This Identity Provider is integrated with Amazon Cognito using OpenID Connect to handle authentication.

If an authentication session is not detected, the web client leverages the AWS Amplify SDK Federated Sign-in workflow to redirect to the Identity Provider that has
OpenIDConnect configured application integrated into the backend infrastructure Cognito Federated Login workflow.

Step 4: Identity Provider Authenticates the Employee

The Identity Provider validates the credentials and checks to see if the employee is associated with the Identity Provider application that is integrated into the
AWS Cognito Backend Infrastructure.

  • If a user exists locally and is already associated with that IdentityProvider identity, it generates short-lived JWT credentials using that identity.
  • If a user does not exist locally, an identity is created, and metadata is pulled from Okta to support that entity’s local data. That new entity is then used to
    generate short-lived JWT credentials.

The identity provider ensures that only legitimate users are authenticated, enforcing appropriate access controls for user accounts to prevent unauthorized access
and impersonation.

Step 5: Authorization code sent back to Browser

Once the code authenticates the user, it sends an authorization code associated with the generated JWT credentials to the browser. The browser then performs a
code exchange, where the authorization code is securely exchanged for new access tokens, ensuring that only the authenticated user receives valid credentials.

Step 6: Access to AWS backend infrastructure

The browser client then calls the AWS Cognito Backend Infrastructure with the authorization code to get back the AWS credentials.

Authenticated user sessions are maintained by securely handling session tokens and enforcing access controls. Sensitive actions, such as changing the user’s
password, are protected by these access controls to ensure only authorized users can modify user accounts.

Designing a Secure Session Token Design Pattern Guide

Conclusion

Session token storage vulnerabilities are one of the most common and dangerous attack vectors in web applications.

There are some implementation methods that can be used:

  • AWS Cognito’s Authorization Code
  • HttpOnly cookies
  • Backend refresh tokens

We can achieve no-token exposure architecture by reducing the attack surface using OWASP provided best practices. This design pattern not only protects the current user sessions but also improves serverless and microservices architecture.

For any organization, ensuring the security of IoT devices is crucial. To protect assets, data, and infrastructure from potential threats, it is important for organizations to implement robust security measures for their IoT devices. By implementing such measures, organizations can reduce the risk of successful attacks and minimize the impact in case of an incident.

eInfochips has played a pivotal role in assisting companies in managing security products on a global scale. We specialize in securing connected device networks across various layers, including device connectivity and applications. Our strategic, transformational, and managed operations approaches have enabled us to provide comprehensive cybersecurity expertise. This includes threat modelling and conducting Vulnerability Assessment and Penetration Testing (VAPT) across OT/IoT devices, operating systems/firmware, web/mobile applications, data, and cloud workloads. Our practices align with industry standards, regulations, and guidelines such as NIST, ENISA, OWASP, MITRE, and the IoT Security Foundation.

Picture of Hardik Gohil

Hardik Gohil

Hardik Gohil works as an engineer in the Cybersecurity domain at eInfochips. He has more than 2 years of experience in Cyber Security and Web application development including application security, Vulnerability Management, Risk Management, and secure code development.

Author

  • Hardik Gohil

    Hardik Gohil works as an engineer in the Cybersecurity domain at eInfochips. He has more than 2 years of experience in Cyber Security and Web application development including application security, Vulnerability Management, Risk Management, and secure code development.

Explore More

Talk to an Expert

Subscribe
to our Newsletter
Stay in the loop! Sign up for our newsletter & stay updated with the latest trends in technology and innovation.

Download Report

Download Sample Report

Download Brochure

Start a conversation today

Schedule a 30-minute consultation with our Automotive Solution Experts

Start a conversation today

Schedule a 30-minute consultation with our Battery Management Solutions Expert

Start a conversation today

Schedule a 30-minute consultation with our Industrial & Energy Solutions Experts

Start a conversation today

Schedule a 30-minute consultation with our Automotive Industry Experts

Start a conversation today

Schedule a 30-minute consultation with our experts

Please Fill Below Details and Get Sample Report

Reference Designs

Our Work

Innovate

Transform.

Scale

Partnerships

Quality Partnerships

Company

Products & IPs

Privacy Policy

Our website places cookies on your device to improve your experience and to improve our site. Read more about the cookies we use and how to disable them. Cookies and tracking technologies may be used for marketing purposes.

By clicking “Accept”, you are consenting to placement of cookies on your device and to our use of tracking technologies. Click “Read More” below for more information and instructions on how to disable cookies and tracking technologies. While acceptance of cookies and tracking technologies is voluntary, disabling them may result in the website not working properly, and certain advertisements may be less relevant to you.
We respect your privacy. Read our privacy policy.

Strictly Necessary Cookies

Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.