Authorisation and Authentication + Keel

Authorisation and Authentication + Keel

Name and title

6 Feb 2022

JSON Web Tokens, commonly referred to as JWTs, have emerged as a pivotal solution in the realm of web security, particularly for authentication and authorization purposes. Originating as a compact and URL-safe way to represent information exchanged between two parties, JWTs have found their footing in the digital landscape due to their self-contained nature, which ensures that all necessary data is embedded. This self-containment facilitates a stateless authentication mechanism, a stark departure from traditional session-based authentication methods that rely heavily on server-side storage.

At a fundamental level, JWT is a string of characters—that encapsulates a claim. In the context of JWT, a claim denotes a statement or assertion about an entity, typically a user, coupled with additional data pertinent to the application's domain. The very design of JWT, emphasizing compactness and versatility, makes it apt for various roles, be it handling user authentication, and enabling data transfers in web applications.

Inside a JWT

A typical JWT looks like this:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

They're 3 base64-encoded strings, split by dots. Diving into the structure of a JWT reveals its tripartite composition. Every JWT is comprised of a header, a payload, and a signature: these are the parts split by dots.

If we were to decode the first part (the header), using some code like:

const header = JSON.parse(atob("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9"));

We’d get the following object:

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

The header often describes the type of the token and the cryptographic algorithm employed to secure its contents. This is essential as JWTs can leverage a variety of algorithms, ranging from HMAC to RSA, each offering different security guarantees and computational requirements.

The payload, on the other hand, is the heart of the JWT. It houses the claims, which can be user attributes, roles, permissions, or any other piece of data that the issuer deems necessary. While there's a set of predefined, standard claims, JWT does not impose restrictions, allowing issuers to define custom claims tailored to their application's needs.

If we were to decode the second part (the claims), using some code like:

const claims = JSON.parse(atob("eyJuYW1lIjoiVGVqdSBLdW1hciIsImtlZWwiOiJ2ZXJ5IGdvb2QifQ")

We'd get the following object:

{ "name": "Teju Kumar", "keel": "very good" }

Lastly, the signature serves as a cryptographic seal of authenticity. It's generated by combining the header, the payload, and a secret using the algorithm specified in the header. The presence of the signature ensures that the JWT remains tamper-proof, as any alteration would invalidate the signature. It's this signature that instills trust in the recipient, assuring them that its contents are genuine and haven't been altered since issuance. This is because the signature is signed using a secret known only to the issuer (the server), and thus, the recipient (the same server but later) can verify the signature using the same secret.

The typical flow of JWT in a web application paints a picture of its efficacy. When a user logs into an application, their credentials are verified by the server. Upon successful verification, instead of creating a session and storing its details on the server, the server generates a JWT that encapsulates the user's information and perhaps some additional metadata. This is then sent back to the client, who retains it for subsequent interactions. For every subsequent request, the client attaches this JWT, usually in the request headers. The server, upon receiving the request, decrypts and verifies the JWT. If it is valid, the server processes the request, all without ever needing to maintain any session-related data.

Yet, as with any technology, JWT is not devoid of challenges. Its self-contained nature means that if it's intercepted or stolen, the thief has access to all the embedded information until the it expires. This emphasizes the importance of short-lived tokens and secure transmission, often via HTTPS.

HTTPS

In the early days of the web, data exchanged between a user's browser and a web server was transmitted in plain text using the HTTP protocol. While functional, this model was fundamentally flawed from a security standpoint. Any eavesdropper, be it a malicious hacker or a nosy internet service provider, could intercept and read the transmitted data with ease—like random JSON objects you send to APIs. This posed a severe risk, especially when sensitive information like passwords, credit card numbers, or personal details were involved.

Enter HTTPS. At its core, HTTPS is a combination of HTTP and SSL/TLS protocols. The SSL (Secure Sockets Layer) and its successor, TLS (Transport Layer Security), introduce robust encryption into the data transmission process. This encryption ensures that even if the data packets are intercepted during transit, they remain indecipherable to unauthorized parties. Only the intended recipient, possessing the correct decryption key, can decode and access the actual content.

But the significance of HTTPS extends beyond mere encryption. One of the foundational aspects of the protocol is the concept of authentication. When you connect to a website using HTTPS, the website presents a digital certificate issued by a trusted third party known as a Certificate Authority (CA). This certificate serves as a testament to the website's authenticity. In essence, it assures the user that they are indeed communicating with the genuine website and not a malicious imposter. This authentication mechanism is especially crucial for websites where trust is paramount, such as online banking, e-commerce platforms, or official government sites. But how does this work?

Certificates and Keys

When you open a browser and try to visit a secure website, like "keel.so," you're essentially trying to send and receive secure "letters" (data) with that website. To ensure the letters are secure, you both need a special method of locking and unlocking them.

Here's where Certificate Authorities (CAs) come into play. These are trusted organizations that vouch for the authenticity of websites.

A digital certificate, often likened to a digital passport or ID, is an electronic document that contains various pieces of information about the entity it represents, in this case, a website. The certificate is structured based on a standard called X.509, which dictates what kind of information a certificate should contain.

Among the various pieces of information in the certificate, the most crucial is the public key of the website. This public key is the cornerstone of the secure communication process. When the website wants to establish a secure connection with a browser, it offers this public key as a means for the browser to encrypt sensitive information that only the website can decrypt using its corresponding private key.

So, how is the public key incorporated into the certificate?

When "keel.so" decides it wants a digital certificate, it first generates a pair of cryptographic keys: a public key and a private key. The public key is intended to be shared, while the private key is kept secret. "keel.so" then creates a Certificate Signing Request (CSR), which includes details about the website and its public key.

This CSR is sent to a Certificate Authority (CA) for approval. The CA verifies the identity of "Keel"before issuing a digital certificate. This verification process ensures that the website or organization is genuine and not attempting to deceive users. The rigor and depth of this verification can vary based on the type of certificate being requested, but let's break down the general process:

  1. Domain Validation (DV): This is the most basic level of validation. The CA checks if the entity applying for the certificate has control over the domain in question. This is often done by sending an email to an address associated with the domain (like admin@keel.so) or asking the applicant to create specific DNS records or upload a file to their website. If the applicant successfully follows the instructions, the CA is reasonably sure they have control over the domain.

  2. Organization Validation (OV): This involves more rigorous checks. In addition to verifying domain control, the CA checks the actual organization's existence. This may involve cross-referencing the organization's details with official business registries or databases. The CA might request documents that prove the organization's legal existence, like articles of incorporation, licenses, or utility bills to confirm the physical location.

  3. Extended Validation (EV): This is the most stringent level of validation. The CA conducts a thorough investigation into the organization, similar to OV but more detailed. They may verify the operational existence (ensuring the company is actively conducting business) and the physical presence of the organization. The CA might also confirm the organization's exclusive rights to use the domain and ensure that no other entity has rights to that name, preventing potential trademark disputes. Often, there's direct communication between the CA and the organization, bypassing standard means of communication like generic email, to ensure they're dealing with the actual organization and not an imposter.

The goal of these verification processes is to establish trust. When you see a website has an SSL/TLS certificate, especially an OV or EV certificate, you can be more confident in the site's authenticity. It means they've gone through a rigorous process to prove they are who they say they are. The green padlock or the company's name in the browser's address bar (especially seen with EV certificates) serves as a sign of this trust and verification.

If everything checks out, the CA then takes the public key from the CSR and incorporates it into the digital certificate. The CA then signs this certificate with its own private key, effectively endorsing the authenticity of the certificate and its contents.

Once issued, the digital certificate, which now contains the website's public key, is installed on the web server of "keel.so." When browsers connect to the site, the server presents this certificate, allowing browsers to access the public key and establish a secure connection. In essence, the digital certificate serves as a secure container and a vouched-for mechanism to deliver the website's public key to anyone wishing to communicate safely with that website.

Now, when you type "keel.so" into your browser:

  1. The website presents its certificate, which includes the public key and the CA's signature.

  2. Your browser, which comes pre-loaded with a list of trusted CAs, checks the signature on the certificate to ensure it's legit. If it recognizes and trusts the CA's signature, it believes the public key truly belongs to "keel.so."

  3. Now that your browser trusts the website, it uses the provided public key to start a secure communication. This involves creating a unique "session key" for that particular interaction. The session key is encrypted using the website's public key and sent back.

  4. "keel.so" uses its private key (the secret unlocking method) to decrypt the session key. Now, both your browser and the website have the same session key, which they use to encrypt and decrypt the data they exchange.

  5. All the information exchanged during this session is protected using this session key. Even if someone intercepts the data, they can't understand it because they don't have the session key.

CAs play a crucial role in ensuring that websites are genuine and that the data exchanged between browsers and websites remains confidential. Your browser's role is to verify that trust and establish communication using the keys provided.

Another often underappreciated advantage of HTTPS is data integrity. Data integrity ensures that the content sent from the server to the client (or vice versa) hasn't been tampered with during transit. Without this guarantee, there's a lurking danger of man-in-the-middle attacks where malicious actors can alter the content of messages in transit. With HTTPS, such tampering becomes immediately evident, and the altered data packets are discarded.

As the modern web evolved, with the rise of online commerce, social media, and digital communication platforms, the amount of personal and sensitive information being exchanged skyrocketed. The privacy implications of this data flow are profound. HTTPS plays a pivotal role in safeguarding user privacy. By encrypting the data, it ensures that prying eyes, whether hackers or even governments, cannot easily surveil or profile users based on their online activities.

Furthermore, in an era marked by increasing concerns about data breaches and cyberattacks, the credibility and trustworthiness of a platform have become paramount. Users are more informed and cautious about their online interactions. Here, HTTPS serves not just as a security protocol but also as a badge of trust. Websites encrypted with HTTPS often display a padlock symbol in the address bar, a universally recognized symbol of security. For businesses, this can directly influence user trust, brand credibility, and even conversion rates.

The transition to HTTPS has also been propelled by technological giants and stakeholders in the digital ecosystem. Browsers like Chrome and Firefox have started marking non-HTTPS sites as 'Not Secure,' nudging both developers and users towards a safer web. Search engines like Google have integrated HTTPS as a ranking factor, incentivizing websites to adopt the HTTPS protocol for better search visibility.

Ultimately, HTTPS is not just a technical protocol; it's the bedrock of a secure, trustworthy, and private internet. As cyber threats become more sophisticated, and as users become increasingly conscious of their digital privacy, the role of HTTPS as the guardian of online communication will only become more pronounced. Adopting HTTPS is no longer a luxury or an afterthought—it's a necessity for any platform or business that operates in the digital realm.

Short Lived Tokens

At the heart of the argument for short-lived JWTs is the basic principle of minimizing risk. JWTs are potential security liabilities by design. If malicious actors obtain them, they gain unauthorized access to resources. While various measures can be employed to protect them, one of the simplest and most effective strategies is to limit their lifespan. By doing so, even if an attacker procures a token, they have only a narrow window of opportunity to misuse it.

Short-lived JWTs also allow for enhanced user security: frequent renewals mean that users' sessions are continually validated. If a user's credentials change or their account undergoes modifications, the effects are rapidly reflected in their session, ensuring that outdated or potentially insecure sessions are terminated swiftly.

Moreover, in the case of a prolonged system breach where tokens are continually leaked, short-lived ones ensure that attackers cannot maintain a persistent foothold within the system. With each JWT having a limited lifespan, attackers would need to constantly acquire new ones, increasing their chances of detection.

Some challenges associated with short-lived JWTs include:

  1. Infrastructure Overhead: Continually issuing, verifying, and renewing JWTs can introduce additional loads on authentication servers. Systems need to be optimized to handle these operations efficiently.

  2. Renewal Mechanisms: Implementing seamless renewal mechanisms, especially in distributed systems or applications with microservices architectures, can be complex.

  3. Revocation: One of JWTs' inherent challenges, exacerbated by short lifespans, is the lack of a built-in revocation mechanism. While they will expire quickly, there might be scenarios where immediate revocation is required. Handling such cases requires additional strategies, like secret rotation.

By limiting the exposure window, short-lived JWTs inherently reduce the potential damage of leaks. When paired with complementary strategies like refresh tokens, they offer a balanced blend of security and usability.

While the security benefits of short-lived JWTs are evident, they must be balanced against usability concerns. Continually expiring and renewing them can potentially disrupt user experiences. For instance, if a user is in the middle of a task and their JWT expires, forcing them to re-authenticate can be jarring. Hence, it's crucial to engineer solutions that seamlessly handle renewals without compromising user experience.

Refresh Tokens

To address the potential usability issues of short-lived JWTs, many systems employ refresh tokens. Usually longer-lived than the primary JWT, these allow a system to issue a new JWT when the old one expires. This way, even if the JWT is very short-lived, users can maintain their sessions without needing to manually re-authenticate. However, it's crucial to protect refresh tokens rigorously, given their power and extended lifespan.

At their core, they are special kinds of JWTs explicitly designed to obtain a new access token, shortly before the existing one expires. Unlike the access token, which is frequently used to authorize requests to an API, the refresh token is used solely for authentication purposes and is submitted to an authentication server to grant a new access one when required.

When a user first authenticates, they receive both an access and a refresh token. The access token might have a short lifespan, say 15 minutes, after which it's no longer valid. However, instead of prompting the user for their credentials again, the application can submit the refresh token to the authentication server. If this is valid, the server issues a new access token, allowing the user to continue their session seamlessly.

Refresh tokens bring several security advantages:

  1. Limited Exposure: Even if an attacker manages to obtain an access token, its short lifespan means potential harm is limited. While an attacker might target the more durable refresh variant, using it typically requires an interaction with the authentication server, increasing the likelihood of malicious activities being detected.

  2. Revocation Capabilities: One of the inherent challenges with JWTs is their lack of a built-in revocation mechanism. Refresh tokens can bridge this gap. Since obtaining a new access token requires interaction with the authentication server, one can implement logic on the server to reject requests from compromised or old refresh tokens, effectively revoking them.

  3. Rotation: For added security, some systems implement rotating refresh tokens. This means that each time one is used to obtain a new access token, a new refresh token is also generated and provided. This ensures that even if one is compromised, it's only valid for a single use.

From a usability standpoint, refresh tokens are invaluable. They offer users the ability to maintain extended sessions—akin to "staying logged in" on a platform—without compromising security. This is especially crucial for mobile applications and other platforms where frequent re-authentication would severely degrade user experience.

While refresh tokens offer many advantages, they're not without their challenges:

  1. Storage Dilemma: Storing refresh tokens securely is paramount. Unlike access ones, which are short-lived and can occasionally be stored in less secure areas like browser storage, refresh tokens, given their longevity and power, require more secure storage solutions, like SameSite httpOnly cookies.

  2. Compromise Scenarios: While refresh tokens can mitigate the damage of compromised access tokens, if the refresh token itself is compromised, the attacker can continually obtain valid access tokens. This necessitates close monitoring of authentication servers for suspicious activities.

  3. Complexity: Implementing a refresh token system introduces added complexity to the authentication flow. Systems must be designed to handle rotations, potential revocations, and the concurrent validity of multiple JWTs.

For organizations looking to implement refresh strategies, several best practices can enhance security and usability:

  • Use HTTPS: Always transmit refresh tokens over secure channels to prevent interception.

  • Regularly Rotate: Implement rotation to ensure that each JWT is used just once.

  • Monitor for Suspicious Activity: Keep an eye on your authentication servers for unusual patterns, such as frequent refresh requests from a single user, which could indicate theft.

  • Offer User Control: Allow users to view and manage their active sessions, providing options to manually revoke them if they believe their security is compromised.

  • Limit Scope: Access tokens often come with specific scopes or permissions (e.g., read, write). Ensure that refresh tokens have minimal scopes, restricted only to obtaining new access tokens.

In the intricate dance of web security and usability, refresh tokens play a pivotal role, ensuring that as we bolster our defenses against cyber threats, we don't alienate our users with cumbersome authentication processes. By understanding the nuances of refresh tokens and implementing them judiciously, organizations can offer their users a seamless digital experience underpinned by robust security mechanisms.

Summary

JWTs have revolutionized web security, providing a compact, URL-safe means of representing information between two parties. Their self-contained design ensures all crucial data is housed within them, allowing for a stateless authentication process. This contrasts sharply with traditional session-based methods which depend on server-side storage. JWTs stand as a testament to the evolution of web security, catering to various roles and ensuring users and applications can trust the data they exchange.

In the ever-evolving landscape of web technology, JWTs have carved a niche for themselves, bridging the gap between security and efficiency. Their design, which emphasizes both compactness and versatility, makes them indispensable in today's digital world. As web security continues to face new challenges, tools like JWTs will remain at the forefront, safeguarding our online interactions and ensuring data integrity. As we move forward, it's imperative for developers and organizations to harness the power of JWTs, ensuring a safer and more seamless digital experience for all users.

Together, we build businesses that thrive

Join the waiting list for early access to Keel

© 2023 Planko Ltd

Together, we build businesses that thrive

Join the waiting list for early access to Keel

© 2023 Planko Ltd

Together, we build businesses that thrive

Join the waiting list for early access to Keel

© 2023 Planko Ltd