JSON Web Tokens

Secpy Community
InfoSec Write-ups
Published in
9 min readOct 19, 2022

--

Written by: Anshul vyas

Introduction

An open industry standard called JSON Web Token is used to exchange data between two entities, often a client (like the front end of your app) and a server (like the back end of your app). They include JSON objects that include the necessary information to be communicated. To ensure that the JSON contents, also known as JWT claims, cannot be changed by the client or an unsavory party, each JWT is additionally signed using cryptography (hashing).

Tokens

You might be asking why the authentication server converts the data into a “token” rather than just sending it as a normal JSON object. The client application’s APIs wouldn’t be able to confirm that the material they are
getting is accurate if the auth server sent it as plain JSON. The application’s APIs would have no way of knowing, for instance, if a hostile attacker changed the user ID (sub claim in the JSON example above). Because of this security concern, the auth server must communicate this data in a fashion that the client application can verify. This is where the idea of a “token” enters the picture.

A token is a string that includes data that can be safely checked, to put it simply. It may consist of a random sequence of alphanumeric characters that lead to an ID in the database or it may be encoded JSON that the client may self-verify (known as JWTs).

JSON Web Tokens Structure

There are three components make up a JWT:

  • Header: Divided into two sections-
    1. The signing method that is being applied.
    2. The kind of token, which is generally “JWT” in this case.
  • Payload: The assertions are in the payload. A list of registered claims includes terms like “issuer”, “expiration period”, “subject” and “aud” (audience). Although not required, these claims offer a set of practical, interoperable assertions. Additional parameters that establish bespoke claims, such as employee role, may also be included in the payload. Usually, the OpenID Connect user subject is created using the topic claim. The Liberty JVM server may be set up to utilize a different claim, though. The second component of the JWT is the payload, which has been Base64Url encoded.
  • Signature: A string that is produced by a cryptographic technique that can be used to check the integrity of the JSON payload is known as a signature.

How is signature is used to ensure Authentication

In order to ensure authentication, we use the signature:

  1. User sends login and password to an authentication server, which may or may not be our application server but is usually a different server.
  2. The authentication server verifies the entered username and password, then generates a JWT token with the user’s technical identity and an expiration timestamp as part of the payload.
  3. Using a secret key, the authentication server signs the header and payload before sending it back to the user’s browser (we will cover later the exact details on how the signature works)
  4. The browser takes the signed JWT and begins delivering it to our Application server with each HTTP request.
  5. The signed JWT essentially serves as a temporary user credential, taking the place of the username and password, which serves as the permanent credential.

Where to Store JSON Web Tokens

I will attempt to touch on it briefly, but because I am not an expert in security, I would rather direct you to other outside sources. JWTs are passports, so keep that in mind at all times. Someone who gains access to one of your user’s tokens has the ability to submit requests on your behalf. It’s not good. Token storage in local storage is quite common since it is convenient. This, however, is not the safest course of action. It has
a high risk of XSS (Cross-Site Scripting). It would be better to save your tokens in a HttpOnly cookie rather than a standard cookie. Although it would be more resistant to XSS assaults, CSRF attacks would still be possible. Obviously, this can provide irksome CORS policy difficulties, but hey, we are dealing with security here.

What If I Want to Encrypt My Tokens Anyway?

In some circumstances, you may wish to encrypt your token in order to stop hijackers from reading your claims. The majority of the time, server-to-server communication uses this. That is completely OK; feel free to encrypt your token as you choose as long as the other end can safely decode and display the token. In either case, keep in mind that using HTTPS for communication is required and greatly improves communication security.

EXAMPLE:

eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiSm9lIENvZGVyIn0.5dlp7GmziL2QS06sZgK4mtaqv0_xX4oFUuTDh1zHK4U

Our individual sections are broken down as follows:

eyJhbGciOiJIUzI1NiJ9 # header .
eyJuYW1lIjoiSm9lIENvZGVyIn0 # payload .
5dlp7GmziL2QS06sZgK4mtaqv0_xX4oFUuTDh1zHK4U #signature

How do JSON Web Tokens work?

To demonstrate how JSON Web Token functions, let’s take the example of a user login. You must define a secret key (referred to as “secret”) before utilising a JWT. Once a user has provided their login details successfully, the JWT will be returned together with the key and kept locally. To guarantee that the data is secure, this transmission should happen over HTTPS.

The JWT will be delivered as a parameter or authorization header from the user agent whenever the user tries to access a protected resource, such as an API or a protected route. After a successful review, the communication partner can decrypt the JSON Web Token and execute the query.

What are JSON WEB TOKENS used for?

JWTs provide a few benefits over conventional cookie-based methods for
authentication and authorisation. This has contributed to their acceptance in the following contexts:

  • Applications using REST: Since the authentication information is supplied along with the request, rest apps ensure stateless protocols.
  • Sharing of resources between origins: JWTs transmit data as part of sharing of resources across origins. Compared to cookies, which often cannot be delivered as part of this procedure, this offers a significant benefit.
  • Use in different contexts: JWT is standardised. Data linked to authentication can be more readily exchanged if you use many frameworks.

Steps to Create a JSON Web Token

The subsequent actions are taken in order to establish a JWT. In situations where there are no relationships between the inputs and outputs of the processes, the order of the phases is not important.

  1. Make the desired claims part of a JWT Claims Set. It should be noted that whitespace is expressly permitted in the representation and that there is no requirement to canonicalize the representation before encoding.
  2. Make the JWT Claims Set's UTF-8 representation of the message’s octets.
  3. Make the appropriate set of header parameters into a JOSE header. It is required that the JWT adhere to the [JWS] or [JWE] standard. It should be noted that whitespace is expressly permitted in the representation and that there is no requirement to canonicalize the representation before encoding.
  4. There are two scenarios depending on whether the JWT is a JWS or JWE: Create a JWS using the message as the JWS payload if the JWT is a JWS; the instructions in [JWS] for constructing a JWS MUST be followed.
    * Otherwise, if the JWT is a JWE, build a JWE using the message as the plaintext, making sure to follow all the instructions in [JWE] for doing so.
  5. Return to Step 3 using a "cty" (content type) value of “JWT” in the new JOSE Header produced in that step if a nested signing or encryption operation will be carried out. Let the message be the JWS or JWE.
  6. If not, make the resultant JWT the JWS or JWE.

Steps for Validating a JSON Web Token

These actions are taken while verifying a JWT. In situations where there are no relationships between the inputs and outputs of the processes, the order of the phases is not important. The JWT MUST be refused, or handled by the application as an invalid input, if any of the specified stages fail.

  1. Make sure there is at least one period (‘.’) character in the JWT.
  2. Make the JWT section that comes before the first period (‘.’) character the Encoded JOSE Header.
  3. Base64url decode the encoded JOSE header while keeping in mind that no extra characters, such as whitespace or line breaks, were utilised.
  4. Confirm that the octet sequence that results is a UTF-8-encoded representation of an entirely legitimate JSON object that complies with RFC 7159 [RFC7159]; the JOSE Header should be this JSON object.
  5. Check that only parameters and values whose syntax and semantics are supported and understood, or that are designated as being disregarded when not understood, are included in the final JOSE Header.
  6. Use one of the techniques outlined in Section 9 of [JWE] to determine whether the JWT is a JWS or a JWE.
  7. There are two scenarios depending on whether the JWT is a JWS or JWE:
    * If the JWT is a JWS, validate the JWS in accordance with [JWS instructions. ]’s. Let the JWS Payload’s base64url decoding produce the Message.
    * Otherwise, if the JWT is a JWE, proceed with [JWEinstructions ]’s for verifying a JWE. Let the resultant plaintext be the Message.
  8. If the “cty” (content type) value in the JOSE Header is “JWT,” the message is a JWT that has undergone nested signature or encryption processes. In this situation, go back to Step 1 and substitute the Message for the JWT.
  9. If not, base64url decode the message while observing the requirement that no extra characters — such as whitespace or line breaks — have been utilised.
  10. Confirm that the octet sequence produced is a UTF-8-encoded representation of an entirely legitimate JSON object that complies with RFC 7159 [RFC7159]; the JWT Claims Set should be this JSON object.
  11. Finally, keep in mind that the choice of algorithms that may be applied in a certain situation is up to the application. Even if a JWT can be properly validated, the application SHOULD refuse the JWT unless the algorithms employed in the JWT are acceptable to the application.

Advantages of JWTs

Using a JWT has a lot of benefits, including the following:

Secure: JWTs are protected from being altered by the client or an attacker thanks to digital signatures that use either a secret (HMAC) or a public/private key combination (RSA or ECDSA).

Stored on the client’s storage: JWTs are created on the server, then sent to the client. The JWT is then sent by the client along with each request. This reduces database space use.

Effective/Stateless: Since a JWT doesn't call for a database search, it can be verified quickly. Particularly in big dispersed systems, this is helpful.

Disadvantages of JWTs

Some disadvantage of using a JWT are:

Non-revocable: Since JWTs are self-contained and verified using stateless technology, it might be challenging to cancel one before it naturally expires. Therefore, it is difficult to carry out measures like instantly banning a user. Having said that, there is a technique to keep the JWT deny / black list up to date, and by doing so, we can revoke them right away.

Reliant on a single secret key: One secret key is necessary for the construction of a JWT. Attackers can create their own JWTs that the API layer will accept if that key is compromised. This suggests that the attacker can impersonate any user's identity if the secret key is compromised. By periodically changing the secret key, we can lower this danger.

Conclusion

JWT is considerably simpler than other web tokens since it is based on JSON, which is simpler to grasp than XML. Other web tokens include Simple Web Tokens (SWTs) and Security Assertion Markup Language (SAML). The JSON will be even lower in size than SAML if we encrypt it, making it simpler to pass in HTML and HTTP contexts. SWTs employ a single key for security, but JWT and SAML both use a public and private key pair for stronger authentication. When it comes to use, JWTs are prevalent on the Internet. In other words, it is simpler to process on the user's gadgets, whether they be laptops or smartphones.

JSON Web Tokens are a fantastic and safe method of transferring data between several parties in addition to authentication. Everyone can more readily identify the sender of information since JWTs contain signatures. The right key is all you require.

From Infosec Writeups: A lot is coming up in the Infosec every day that it’s hard to keep up with. Join our weekly newsletter to get all the latest Infosec trends in the form of 5 articles, 4 Threads, 3 videos, 2 GitHub Repos and tools, and 1 job alert for FREE!

--

--

SecPy Community aims to change whole environment of Cyber Security and Ethical Hacking with the help of curious minds & build ground-breaking solutions