Blog 07: Misc — JSON Web Token(JWT)

1 year ago 92
BOOK THIS SPACE FOR AD
ARTICLE AD

Hey folks!

I wanted to take a moment to apologize for the lack of updates on the blog recently. As some of you may know, we have been focused on preparing for the exams and unfortunately, this has taken up a significant amount of the time and energy, but now we’re back again with a new energy and a new topic which is JSON web tokens.

Note: we suppose that you have a basic knowledge of how the world wide web works.

HTTP is stateless !
HTTP(Hypertext Transfer Protocol) is a stateless protocol which means that each request made from the client to the server is treated as a standalone request, neither the client nor the server keeps track of the subsequent requests. to overcome the stateless of this protocol we could use either a session or a token .

Authentication is the process of verifying the identity of a user or system. This is typically done through the use of a combination of a username and password, but can also include other methods such as biometric identification, security tokens, or certificates.
The goal of authentication is to ensure that only authorized individuals or systems are able to access sensitive information or perform specific actions.
there is mainly two authentication methods :

Session-based authentication is a way of verifying the identity of a user by creating a session on the server and storing a session ID in a cookie on the client’s browser. When the user makes subsequent requests to the server, the session ID is included in the request(the cookie header is added automatically in every request), and the server uses it to look up the corresponding session and verify the user’s identity.

session-based authentication process

Here’s an example of how session-based authentication could work in a web application:

the user visits the login page of the web application and enters their username and password.The client sends an HTTP POST request to the server, including the user’s credentials in the request body.The server authenticates the user by checking their credentials against the ones stored in the database.If the credentials are valid, the server creates a new session, generates a unique session ID, and stores it in the session data. The server also sets a session ID cookie on the client’s browser.The server sends an HTTP response to the client, including the session ID in the Set-Cookie header.The client receives the response and stores the session ID cookie in their browser.The client makes subsequent requests to the server, including the session ID cookie in the request headers.The server receives the request and uses the session ID to look up the corresponding session data. If the session data is present, the server verifies that the user is logged in and grants access to the requested resources.When the user logs out, the server destroys the session and the client discards the session ID cookie.

Token-based authentication is a method of authenticating a user by providing a token (a string of characters) rather than a traditional login and password. The token is generated by the server and is passed to the client, typically in the form of an HTTP header. The client then includes the token with each subsequent request to the server, allowing the server to authenticate the user and perform authorized actions on their behalf.

and for this methode of authentication we’re going to take JWT standard (RFC 7519) as an example.

what is JWT ?

First, let’s see the definition of JWT defined in the RFC 7519.

JSON Web Token (JWT) is a compact, URL-safe means of representing claims to be transferred between two parties. The claims in a JWT are encoded as a JSON object that is used as the payload of a JSON Web Signature (JWS) structure or as the plaintext of a JSON Web Encryption (JWE) structure, enabling the claims to be digitally signed or integrity protected with a Message Authentication Code (MAC) and/or encrypted.

what we can understand from this definition is that a Json Web Token is a set of claims that can be represented in two forms either JWS or JWE as a way if securing it self. the main difference between JWS and JWE is that everybody can see the payload of JWS while JWE is encrypted.

NB: The suggested pronunciation of JWT is “jot”.

before we deep dive it‘s important to know the connection between JWT, JWS, JWE, JWA, and JWK:

the connection between JWT, JWS, JWE, JWA, and JWK

JSON Web Algorithm (JWA):

JWA(RFC 7518) is a specification that defines a set of algorithms that can be used to secure JSON Web Tokens (JWT) and JSON Web Signatures (JWS).

JWA defines several algorithms for signing and encrypting JWTs, including:

HMAC-based algorithms (HS256, HS384, and HS512) which use a shared secret key for signing and verification.RSA-based algorithms (RS256, RS384, and RS512) which use a public/private key pair for signing and verification.Elliptic Curve-based algorithms (ES256, ES384, and ES512) which use a public/private key pair for signing and verification.

JSON Web Key (JWK):

JWK(RFC 7517) is a JSON data structure that represents a cryptographic key. It is used to securely transmit key information in JSON Web Signatures (JWS) and JSON Web Encryption (JWE) objects.

A JWK typically includes the following properties:

kty” (key type) which specifies the algorithm for which the key is intended, for example “RSA” or “EC”“use” which specifies the intended use of the key, for example “sig” for signing or “enc” for encryption“alg” (algorithm) which specifies the algorithm that should be used with the key, for example “RS256” or “HS256”“kid” (key ID) which is an optional identifier for the key

JSON Web Signature (JWS):

JWS (RFC 7515) is one of the structures used by JWT. and because It is the most common implementation of the JWT we’re not going to dicuss JWE.
let’s take this example provided in the official site https://jwt.io/

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

if we split this string by dot we obtain three elements :

JOSE (JavaScript Object Signing and Encryption) header:

base64 encoded JOSE header

if we base64 decode it we obtain:

Let’s break down the two fields we have in our JWT:

alg” (algorithm): defines the algorithm used to sign the JWT.“typ” (type): defines the media type.

The Payload:
With the JOSE header out of the way, let’s take a look at the second part, the payload.

base64 encoded payload

After we decode it:

the fields(sub,name,iat …) are called claims.
claims are set of information encoded in the token, there are three types of JTW claims:

Registered Claims: are claims that have been documented initially in the RFC 7519 for example:

iss” (issuer) — identifies the entity that issued the JWT

sub” (subject) — identifies the subject of the JWT

aud” (audience) — identifies the intended audience for the JWT

exp” (expiration time) — the time after which the JWT must not be accepted for processing
You can check the complete list here.

Public Claims: are a type of claim that is publicly registered through IETF

You can check the list of public claims here.

Private Claims: can be anything. It’s up to the JWT creator or consumer to determine the claims name and function but you shoud avoid any collision with the predefined claims.

You might wonder how this token still secure even we can see it’s content, but the trick is even that it can be read but we can ensure that he wasn’t altered using signature.
there is a bunch of cryptographic algorithm to sign the token but we will focus on HMAC SHA256.
HMAC (Hash-based Message Authentication Code) is a type of message authentication code (MAC) that uses a cryptographic hash function in combination with a secret key to provide integrity and authenticity of a message. The HMACSHA256 is a specific implementation of HMAC that uses the SHA-256 cryptographic hash function.this secret key will be used for both signing and verification.
here is the signature algorithm:

// signature algorithm
data = base64urlEncode( header ) + “.” + base64urlEncode( payload )

signature = HMAC-SHA256( data, secret_salt )

this is a simple python implementation using pyjwt library:

import jwt
payload_data = {
"sub": "1234577891",
"name": "INSEC",
"iat": 1516249128
}

my_secret = 'My_Sup3r_Secr3t'

token = jwt.encode(
payload=payload_data,
key=my_secret
)

print(token)
#eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.
#eyJzdWIiOiIxMjM0NTc3ODkxIiwibmFtZSI6IklOU0VDIiwiaWF0IjoxNTE2MjQ5MTI4fQ.
#h93VUdnIWFpIsbbPIeutP4KmYKOFlwVfbEA9IF3bsZc

NB:you may notice that we didn’t specified the header because it is by default {“typ”: “JWT”,“alg”: “HS256”}.

to check if our script works fine lets test our token in jwt debugger

decoded token without the signing key

as you can see everything works fine but there is one error Invalid Signature, if you understood well what i explained about signature you gonna notice that we didn’t afford the secret key to the debugger so he used his default key ‘your-256-bit-secret’.

decoded token with the signing key

when we filled the key field with the key used in signature it was verified successfully.

now let’s put all this in practice and see how this JWT’s can be used :

JWT workflow

The basic process for JWT authentication is as follows:

The user signs in using their credentials (username and password) or by using an external authentication provider (such as Google or Facebook).The authentication server verifies the user’s credentials and issues a JWT that is signed using a secret salt or a private key.The user’s client then uses the JWT to access protected resources by including it in the HTTP Authorization header of the request.The resource server then decodes and verifies the authenticity of the token using the secret salt or public key provided by the identity provider.

In summary, JWT authentication is a process in which the identity provider generates a JWT to certify the user’s identity, the user’s client uses the JWT to access protected resources, and the resource server verifies the authenticity of the token using the secret salt or public key provided by the identity provider.

In general, token-based authentication is considered to be more secure than session-based authentication because tokens are more difficult to intercept or steal, and they can be set to expire after a certain period of time.

Tokens also enables to authenticate clients across different domains, which is useful in microservices architectures.

Token-based authentication is also more scalable than session-based authentication because it does not require server-side storage of session data(it is stocked on the browser local storage).

However, it’s important to note that both methods have their pros and cons and the choice of using token-based authentication or session-based authentication depends on the specific use case and the requirements of the application.

Read Entire Article