Application Security – JavaScript Web Tokens

JWT’s and User Initiated Logouts

IoT Device Testing

The following article is a discussion that explores JavaScript Web Tokens, and how developers generate JWT signing keys and how they create, verify, and terminate sessions.

Table of Contents

Background

JavaScript web tokens are well documented and are used for authentication. JWT’s consist of three parts; the header, payload and signature. The header is used to describe the JWT, specifically, it will indicate how the signature is calculated. The payload of the JWT will contain claims about the user presenting the JWT, claims are just another word for attributes. There are a few predesignated claims there should be included in your JWT, other claims can be free form, that means the payload can contain any data that the developer wants it to contain. The signature is used to prevent tampering of the JWT.  The most common signing algorithms are HS256, RS256, and ES256, however, there are other algorithms.  One of the most important claims that should always exist in the payload is the “exp” claim. The “exp” claim represents the epoch time that the JWT will expire, without this claim the JWT is valid forever.

The expiration claim on the JWT introduces an interesting issue with session management, when a user intentionally terminates a session, how do you invalidate the JWT?  A common design pattern that I see on application tests is for the client-side application to receive a JWT from the server and then store it in the browser’s session storage. Subsequent Ajax requests will include the JWT as a bearer token in the authorization header.  When a user intentionally terminates a session, otherwise known as logging out, the application will simply delete the JWT from the browser’s session storage. This has the effect of causing the browser to believe the session was terminated because the application can no longer authenticate to the server since the application can no longer find the JWT in the session store.  However, this is an illusion, deleting the JWT from the session store does nothing to invalidate the session, the deleted JWT will remain valid until the expiration date has been reached. If an attacker had captured the JWT, they would be able to use it until the exp claim lapses.  This type of session handling runs afoul of the OWASP best practices, OWASP states that a secure session termination requires at least the following components.

  • Availability of user interface controls that allow the user to manually log out.
  • Session termination after a given amount of time without activity (session timeout).
  • Proper invalidation of server-side session state.

This leaves the developer with the before mentioned question, how can a JWT be invalidated when the user logs out?  One solution that I have heard is to have short lived expirations and to use a refresh token to re-issue the JWT upon expiration.  While this solution limits the window in which an abandoned session could be used, it doesn’t actually solve the problem.  I have seen a few other recommendations that should work in theory, but they are not always practical or easy to implement. Below I describe the easiest method that I have found.  It makes changes to how developers generate JWT signing keys and how they create, verify, and terminate sessions.

Session Creation

When the session is created, the session key should be generated and stored in the datastore.  For the purposes of this writing, it will be assumed the datastore is a database table with the following fields.

  • SessionID GUID
  • SessionKey TEXT
  • ExpirationDate Timestamp

Once the JWT is populated and ready to be signed, the KID claim should be populated with the SessionID GUID and the JWT should be signed with the SessionKey value as demonstrated with the below pseudo code.

				
					$key = SecureRandom.Generate(32); // 32 random bytes

$id = GUID.New(); // get new 32-bit GUID

$expires = date_add($now, “1h”); // expire in 1 hour

$db.execute(“insert into SessionKeys(SessionID, SessionKey, ExpirationDate) values(?, ?, ?)”, $id, $key,$expires);

$header = {“alg”:”HS256”, “kid”:”$id”}

$payload = {“exp”:”$expires”}; // insert claims here

$jwt = JWT.sign($header, $payload, $key)
				
			

Session Verification

When it is time to verify the JWT, the application should read the KID claim and lookup that value in the database using the below pseudo code.

				
					$qSession = $db.Query(“select * from SessionKeys where SessionID = ?”, $jwt[“kid”]);
				
			

It goes without saying that parameterized statements should always be used when querying a database.

				
					$isvalid = JWT.verify($jwt, $qSession[“SessionKey”]);
				
			

Session Termination

When the user initiates a logout, the JWT verified using the process outlined above and then the session key should be deleted from the database as shown in the below pseudo code.

				
					$qSession = $db.Query(“select * from SessionKeys where SessionID = ?”, $jwt[“kid”]);

$isValid = JWT.verify(jwt, qSession[“SessionKey”]);

If($isValid)

{

               $db.execute(“delete from SessionKeys where SessionKey = ? or ExpirationDate <= ?”, $qSession[“SessionID”], $now);

}
				
			

By deleting the session key, the JWT is no longer able to be validated and is now in a de facto state of being expired.  The “or ExpirationDate <= $now” portion of the above pseudo code does some automated garbage collection by deleting the current session and any sessions that have already expired.  At this point, it is safe for the client-side application to delete the JWT from session storage.

Conclusion

JWTs are a convenient way to implement authentication, however they are not without their complexities, managing JWTs can be likened to managing PKI.  With PKI, it can be difficult to invalidate certificates once they are issued, revocations require a whole other process (CRLs) to maintain a healthy PKI.  The same can be said for managing JWT’s, however, the revocation process can be simplified using the process outlined in this writing.

Picture of Anthony Cole

Anthony Cole

Anthony Cole is a Sr. Security Consultant with over 22 years of experience in information technology, IT security and software development. Anthony is fully GIAC certified in all facets of information security, enabling him to facilitate successful outcomes for customers. Anthony’s vast knowledge of both offensive and defensive security ensures that Redbot Security’s customers will receive the best service in the industry.

Anthony is Redbot Security’s AppSec SME and formerly a Sr. Level Application Penetration Testing Engineer for NetSpi and Presidio as well as Blutique LLC’s Chief Technical Officer and Sr. Application Developer.

REDBOT SECURITY

Deep-Dive Penetration Testing

Senior Level Hands-on-Keyboard

Manual Testing

Get a Project Quote

Related Articles

Ransomware Nightmare

Android Malware

The likelihood of a cyber attack on a mobile platform is significantly high, but how difficult is it for a malicious actor to generate malware? You might be surprised.

Read More »
IDOR Fix

Insecure Direct Object Reference (IDOR)

Insecure Direct Object Reference (IDOR) vulnerabilities pose a significant risk to the security of web applications, allowing attackers unauthorized access to sensitive data and functionalities. By understanding the implications of IDOR and adopting secure coding practices, web developers can protect their applications and users from potential exploitation.

Read More »
mass assignment vulnerability- Web Application Security

Mass Assignment Vulnerabilities

Mass Assignment Vulnerability occurs when a web application allows users to submit a more extensive set of data than is intended or safe. The potential consequences of this vulnerability can be severe

Read More »
How to prevent active directory attack

AS-REP Roasting

Kerberos Authentication Service Response (AS-REP) Roasting, a technique similar to Kerberoasting, has gained prominence as a method for attackers to compromise Active Directory (AD) authentication systems.

Read More »
2024 FBI IC3 Report Analysis

2024 FBI IC3 Report Analysis | Redbot Security’s Cyber Insights

The FBI released its FY 2024 IC3 Annual Report on April 24, 2025, detailing 859,532 complaints and a record $16.6 billion in losses. In this post, we highlight how phishing, BEC, and cryptocurrency fraud continue to surge, why ransomware remains a top threat to critical infrastructure, and which demographics are most at risk. Plus, discover Redbot Security’s proven strategies,from manual penetration testing to red teaming, that can help you turn IC3 data into actionable defenses.

Read More »
Best Penetration Testing Companies

Internal Network Penetration Testing | Redbot Security

Internal network penetration testing is essential for identifying security gaps within an organization’s infrastructure. Attackers exploit misconfigured permissions, weak credentials, and unpatched vulnerabilities to escalate privileges and move laterally within networks. A thorough penetration test helps uncover these risks before they are exploited, ensuring stronger security controls, improved access management, and compliance with industry standards. Redbot Security’s expert-led penetration testing provides in-depth assessments to fortify your internal network against evolving threats.

Read More »
The Impact of Data Breach

The Impact of a Data Breach

Increasingly, investors see proactive cybersecurity spending as a hallmark of strong corporate governance. It can be factored into how they value a company’s resilience and risk profile

Read More »
Red Team vs Penetration Testing

Evolving Your Cybersecurity: From Penetration Testing to Red Teaming

While penetration testing is valuable in identifying technical vulnerabilities, red teaming provides a more holistic assessment by simulating realistic threat scenarios. By embracing red teaming, organizations can bolster their defenses, uncover weaknesses, and stay one step ahead of sophisticated adversaries.

Read More »
Common Attacks

Microsoft Windows Laptop Security

Malicious actors prey on weak configurations like locusts. Microsoft, despite knowing that their operating systems, have inherent weaknesses have done little to enhance their initial security outside of remediation for publicly known vulnerabilities.

Read More »
Network Pen Testing Companies

Attack Surface Management (ASM)

Today, cybercriminals have plenty of entry points to exploit. Therefore, it has become crucial for organizations to improve their attack surface visibility to have more effective protection. This is where attack surface management (ASM) comes into play. This article will explore all about attack surface management (ASM), including its importance, working principle, and benefits.

Read More »

Additional Articles
that you may find helpful

Cyber threat news feed

Check out the latest cybersecurity news around the globe

Cymbiotic will provide unparalleled security insight with the ability to manage teams, clients, on-demand testing with rapid internal VM deployment […]

Pen-Test Project Quote

Penetration Testing Service Provider

Our expert team will help scope your project and provide a fast and accurate project estimate.

Contact Redbot Security

Security Management Platform

Cymbiotic is a revolutionary, scalable platform providing unparalleled security management: on-demand testing, secure reporting, and remediation tracking, while also acting as an advanced attack surface management platform ... for every network.
Show Buttons
Hide Buttons